Ruby:递归方法 [英] Ruby: recursive method
本文介绍了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.
谁能给我解释一下?
推荐答案
- 方法
reverse_append([],4)
被调用 - 由于
4 >= 0
,return
语句不会被调用. - 方法
reverse_append([],3)
被调用. - 由于
3 >= 0
,return
语句不会被调用. - 方法
reverse_append([],2)
被调用. - 由于
2 >= 0
,return
语句不会被调用. - 方法
reverse_append([],1)
被调用. - 由于
1 >= 0
,return
语句不会被调用. - 方法
reverse_append([],0)
被调用. - 由于
0 >= 0
,return
语句不会被调用. - 方法
reverse_append([],-1)
被调用. - 由于
-1 <0
,返回数组([]
). - 我们在调用堆栈中弹出一层,到
n = 0
和arr = []
. arr <<
和 arr
被返回,所以现在arr = [0]
.- 我们在调用堆栈中弹出一层,到
n = 1
和arr = [0]
. arr <<
和 arr
被返回,所以现在arr = [0, 1]
.- 我们在调用堆栈中弹出一层,到
n = 2
和arr = [0, 1]
. arr <<
和 arr
被返回,所以现在arr = [0, 1, 2]
.- 我们在调用堆栈中弹出一层,到
n = 3
和arr = [0, 1, 2]
. arr <<
和 arr
被返回,所以现在arr = [0, 1, 2, 3]
.- 我们在调用堆栈中弹出一层,到
n = 4
和arr = [0, 1, 2, 3]
. arr <<
和 arr
被返回,所以现在arr = [0, 1, 2, 3, 4]
.- 最后,顶级"方法返回,我们得到了最终结果.
- The method
reverse_append([],4)
is called - Since
4 >= 0
, thereturn
statement does not get called. - The method
reverse_append([],3)
is called. - Since
3 >= 0
, thereturn
statement does not get called. - The method
reverse_append([],2)
is called. - Since
2 >= 0
, thereturn
statement does not get called. - The method
reverse_append([],1)
is called. - Since
1 >= 0
, thereturn
statement does not get called. - The method
reverse_append([],0)
is called. - Since
0 >= 0
, thereturn
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
andarr = []
. arr << n
andarr
is returned, so nowarr = [0]
.- We pop up one level in our call stack, to where
n = 1
andarr = [0]
. arr << n
andarr
is returned, so nowarr = [0, 1]
.- We pop up one level in our call stack, to where
n = 2
andarr = [0, 1]
. arr << n
andarr
is returned, so nowarr = [0, 1, 2]
.- We pop up one level in our call stack, to where
n = 3
andarr = [0, 1, 2]
. arr << n
andarr
is returned, so nowarr = [0, 1, 2, 3]
.- We pop up one level in our call stack, to where
n = 4
andarr = [0, 1, 2, 3]
. arr << n
andarr
is returned, so nowarr = [0, 1, 2, 3, 4]
.- Finally, the "top-level" method returns, and we have our final result.
这篇关于Ruby:递归方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文