Ruby:递归方法 [英] Ruby: recursive method

查看:41
本文介绍了Ruby:递归方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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]

我似乎无法理解这种递归方法.它产生一个从 0 到 n 的数组.

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

谁能给我解释一下?

推荐答案

  1. 方法reverse_append([],4)被调用
  2. 由于 4 >= 0return 语句不会被调用.
  3. 方法 reverse_append([],3) 被调用.
  4. 由于 3 >= 0return 语句不会被调用.
  5. 方法 reverse_append([],2) 被调用.
  6. 由于 2 >= 0return 语句不会被调用.
  7. 方法 reverse_append([],1) 被调用.
  8. 由于 1 >= 0return 语句不会被调用.
  9. 方法 reverse_append([],0) 被调用.
  10. 由于 0 >= 0return 语句不会被调用.
  11. 方法 reverse_append([],-1) 被调用.
  12. 由于 -1 <0,返回数组([]).
  13. 我们在调用堆栈中弹出一层,到 n = 0arr = [].
  14. arr <<arr 被返回,所以现在 arr = [0].
  15. 我们在调用堆栈中弹出一层,到 n = 1arr = [0].
  16. arr <<arr 被返回,所以现在 arr = [0, 1].
  17. 我们在调用堆栈中弹出一层,到 n = 2arr = [0, 1].
  18. arr <<arr 被返回,所以现在 arr = [0, 1, 2].
  19. 我们在调用堆栈中弹出一层,到 n = 3arr = [0, 1, 2].
  20. arr <<arr 被返回,所以现在 arr = [0, 1, 2, 3].
  21. 我们在调用堆栈中弹出一层,到 n = 4arr = [0, 1, 2, 3].
  22. arr <<arr 被返回,所以现在 arr = [0, 1, 2, 3, 4].
  23. 最后,顶级"方法返回,我们得到了最终结果.
  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.

这篇关于Ruby:递归方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆