davidhu2000 - 1 year ago 84
Ruby Question

Ruby: recursive method

``````def reverse_append(arr, n)
return arr if n < 0
reverse_append(arr, n-1)
arr << n
arr
end

reverse_append([],4) #=> [0, 1, 2, 3, 4]
``````

I can't seem to understand this recursive method. It produces an array from 0 up to n.

To me, n seems to count down until 0, then counts up one at a time, but I can't see where the counting up occurs.

Can someone please show me how this method produces the result?

1. The method `reverse_append([],4)` is called
2. Since `4 >= 0`, the `return` statement does not get called.
3. The method `reverse_append([],3)` is called.
4. Since `3 >= 0`, the `return` statement does not get called.
5. The method `reverse_append([],2)` is called.
6. Since `2 >= 0`, the `return` statement does not get called.
7. The method `reverse_append([],1)` is called.
8. Since `1 >= 0`, the `return` statement does not get called.
9. The method `reverse_append([],0)` is called.
10. Since `0 >= 0`, the `return` statement does not get called.
11. The method `reverse_append([],-1)` is called.
12. Since `-1 < 0`, the array (`[]`) is returned.
13. We pop up one level in our call stack, to where `n = 0` and `arr = []`.
14. `arr << n` and `arr` is returned, so now `arr = [0]`.
15. We pop up one level in our call stack, to where `n = 1` and `arr = [0]`.
16. `arr << n` and `arr` is returned, so now `arr = [0, 1]`.
17. We pop up one level in our call stack, to where `n = 2` and `arr = [0, 1]`.
18. `arr << n` and `arr` is returned, so now `arr = [0, 1, 2]`.
19. We pop up one level in our call stack, to where `n = 3` and `arr = [0, 1, 2]`.
20. `arr << n` and `arr` is returned, so now `arr = [0, 1, 2, 3]`.
21. We pop up one level in our call stack, to where `n = 4` and `arr = [0, 1, 2, 3]`.
22. `arr << n` and `arr` is returned, so now `arr = [0, 1, 2, 3, 4]`.
23. Finally, the "top-level" method returns, and we have our final result.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download