检测递归方法调用的最佳方法是什么?或许,可以做成这样的格式:
def foo
if some_code_to_detect_recursive_call
...
else
...
end
end
我可以想到一种解析caller
信息的方法,但我有兴趣看看是否有更好的方法。
只需在进入您的方法后增加一个计数器(实例或全局变量)并在退出时减少它。
在入口处,计数器会告诉您您的递归级别。
def is_recursive(max_recursive_calls=2)
calls = caller.inject(0) do |calls, line|
break calls if calls >= max_recursive_calls
calls += 1 if line == caller[-2]
calls
end
calls >= max_recursive_calls
end
# 1
def recursive
p "case #1"
recursive unless is_recursive
end
# 2
def recursive_a
p "case #2.1"
recursive_b unless is_recursive
end
def recursive_b
p "case #2.2"
recursive_a unless is_recursive
end
# 3
def recursive_cond(iter=0, limit=10)
p "case #3"
recursive_cond(iter + 1, limit) unless iter > limit || is_recursive(50)
end
recursive
recursive_a
recursive_b
recursive_cond
p "If you see this: is_recursive function implemented correctly"
"case #1"
"case #1"
"case #2.1"
"case #2.2"
"case #2.1"
"case #2.2"
"case #2.1"
"case #2.2"
"case #3"
"case #3"
"case #3"
"case #3"
"case #3"
"case #3"
"case #3"
"case #3"
"case #3"
"case #3"
"case #3"
"case #3"
"If you see this: is_recursive function implemented correctly"