Suppose I have this code:
def rcall(num)
return 0 if 10 == num
1 + rcall(num - 1)
end
p rcall(90) # => 80
This code will always return 10 less than the value passed into num
, i.e. the count of the recursive calls made.
I can't see how it works. I have a vague understanding that we return zero if the exit condition is met so as not to increment the counter again. But how, exactly, does adding one to the proc call increment the count of times called? I can't see where the incrementer is being accumulated.
Also, is this a technique specific to Ruby architecture, or is it more generally applicable? I haven't seen it mentioned in any answers to questions asking about how to count recursive calls; seems most of the time people pass a counter variable along to keep track of the count.