davidhu2000 - 3 months ago 5x

Ruby Question

`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?

Answer

- The method
`reverse_append([],4)`

is called - Since
`4 >= 0`

, the`return`

statement does not get called. - The method
`reverse_append([],3)`

is called. - Since
`3 >= 0`

, the`return`

statement does not get called. - The method
`reverse_append([],2)`

is called. - Since
`2 >= 0`

, the`return`

statement does not get called. - The method
`reverse_append([],1)`

is called. - Since
`1 >= 0`

, the`return`

statement does not get called. - The method
`reverse_append([],0)`

is called. - Since
`0 >= 0`

, the`return`

statement does not get called. - The method
`reverse_append([],-1)`

is called. **Since**`-1 < 0`

, the array (`[]`

) is returned.- We pop up one level in our call stack, to where
`n = 0`

and`arr = []`

. `arr << n`

and`arr`

is returned, so now`arr = [0]`

.- We pop up one level in our call stack, to where
`n = 1`

and`arr = [0]`

. `arr << n`

and`arr`

is returned, so now`arr = [0, 1]`

.- We pop up one level in our call stack, to where
`n = 2`

and`arr = [0, 1]`

. `arr << n`

and`arr`

is returned, so now`arr = [0, 1, 2]`

.- We pop up one level in our call stack, to where
`n = 3`

and`arr = [0, 1, 2]`

. `arr << n`

and`arr`

is returned, so now`arr = [0, 1, 2, 3]`

.- We pop up one level in our call stack, to where
`n = 4`

and`arr = [0, 1, 2, 3]`

. `arr << n`

and`arr`

is returned, so now`arr = [0, 1, 2, 3, 4]`

.- Finally, the "top-level" method returns, and we have our final result.

Source (Stackoverflow)

Comments