Ruby递归函数 [英] Ruby recursive function
本文介绍了Ruby递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在从递归函数返回值时遇到问题.
I've problem returning value from recursive function.
def ask_question(question)
print question
answer = STDIN.gets.chomp
ask_question question if answer.empty?
return answer
end
第一次正确返回 answer ,但是在下次通话中我得到了空字符串.为什么会这样?
The first time the answer is returned properly but I got empty string in next calls. Why is that?
推荐答案
那是因为您没有返回递归调用 ask_question
所返回的值.
That is because you aren't returning the value returned by your recursive calls to ask_question
.
def ask_question(question)
print question
answer = STDIN.gets.chomp
answer = ask_question question if answer.empty?
return answer;
end
您要做的就是在方法完成后返回第一个用户输入值(在您的情况下为空字符串).
All you were doing is returning the first user input value (in your case an empty string) when the method was done.
这篇关于Ruby递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文