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]
There's a nice tool you can add to many editors called "Seeing Is Believing", which lets you see what is happening as code runs:
def reverse_append(arr, n)
return arr if n < 0 # => false, false, false, false, true
reverse_append(arr, n-1) # => [], [0], [0, 1], [0, 1, 2]
arr << n # => [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]
arr # => [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]
end
reverse_append([], 3) # => [0, 1, 2, 3]
However, with a name like "reverse_append" it seems like you should see a result that is descending in values:
def reverse_append(arr, n)
return arr if n < 0 # => false, false, false, false, true
reverse_append(arr, n-1) # => [], [0], [1, 0], [2, 1, 0]
arr.unshift n # => [0], [1, 0], [2, 1, 0], [3, 2, 1, 0]
arr # => [0], [1, 0], [2, 1, 0], [3, 2, 1, 0]
end
reverse_append([], 3) # => [3, 2, 1, 0]
In either case, there are a lot of easier ways to generate such an array without relying on recursion:
[*0..3] # => [0, 1, 2, 3]
(0..3).to_a # => [0, 1, 2, 3]
[*0..3].reverse # => [3, 2, 1, 0]
(0..3).to_a.reverse # => [3, 2, 1, 0]
Well step through the code with the supplied parameters. The first step is to check if n < 0 which its not. If it isn't 0 reverse append with [], 3 and appends the that array the number and then returns the array.
So it takes the array, adds 4 to it after it has gone through the step of dealing with [], 3, [], 2, [],1 and [], 0. So the first call that will succeed is just returning the array when it gets below 0, next is 0 gets appended, then one, then 2, then 3 and lastly the original call with 4 gets added arr << n.
reverse_append([],4) is called4 >= 0, the return statement does not get called.reverse_append([],3) is called.3 >= 0, the return statement does not get called.reverse_append([],2) is called.2 >= 0, the return statement does not get called.reverse_append([],1) is called.1 >= 0, the return statement does not get called.reverse_append([],0) is called.0 >= 0, the return statement does not get called.reverse_append([],-1) is called.-1 < 0, the array ([]) is returned.n = 0 and arr = [].arr << n and arr is returned, so now arr = [0].n = 1 and arr = [0].arr << n and arr is returned, so now arr = [0, 1].n = 2 and arr = [0, 1].arr << n and arr is returned, so now arr = [0, 1, 2].n = 3 and arr = [0, 1, 2].arr << n and arr is returned, so now arr = [0, 1, 2, 3].n = 4 and arr = [0, 1, 2, 3].arr << n and arr is returned, so now arr = [0, 1, 2, 3, 4].