Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby递归函数_Ruby_Function_Recursion - Fatal编程技术网

Ruby递归函数

Ruby递归函数,ruby,function,recursion,Ruby,Function,Recursion,从递归函数返回值时遇到问题 def ask_question(question) print question answer = STDIN.gets.chomp ask_question question if answer.empty? return answer end 第一次正确返回应答,但在接下来的通话中我得到了空字符串。 这是为什么?这是因为您没有返回递归调用返回给ask\u question的值 def ask_question(question

从递归函数返回值时遇到问题

def ask_question(question)
    print question
    answer = STDIN.gets.chomp

    ask_question question if answer.empty?
    return answer
end
第一次正确返回应答,但在接下来的通话中我得到了空字符串。
这是为什么?

这是因为您没有返回递归调用返回给
ask\u question
的值

def ask_question(question)
    print question
    answer = STDIN.gets.chomp
    answer = ask_question question if answer.empty?
    return answer;
end

您所做的只是在方法完成时返回第一个用户输入值(在您的示例中为空字符串)。

您的代码不起作用,因为您返回的变量
answer
始终是第一次迭代中的变量(每个调用都有自己的局部范围)。因此,一个可能的解决办法是:

def ask_question(question)
    print question
    answer = STDIN.gets.chomp
    answer.empty? ? ask_question(question) : answer
end
请注意,尽管这种递归构造对于支持尾部调用优化的语言来说很好,但Ruby并不强制这样做,因此它通常会为每次迭代创建一个新的堆栈框架,最终会失败。我建议循环,例如:

def ask_question(question)
  loop do 
    print question
    answer = STDIN.gets.chomp
    break answer unless answer.empty?
  end
end

为了证明@tokland的观点,如果您运行程序并按enter键几次,然后按
ctrl+c
(对于*nix),您将看到一个堆栈跟踪,它与按enter键的次数成比例。好的观点,@jeremy。您还可以在UNIX框中运行“yes”“| ruby script.rb”,最终得到“堆栈级别太深(SystemStackError)”。