Ruby: recursive method

前端 未结 3 880
半阙折子戏
半阙折子戏 2021-01-17 06:32
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]
         


        
3条回答
  •  一生所求
    2021-01-17 07:05

    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.

提交回复
热议问题