原始代码有效,如果放入方法则没有?

时间:2013-11-08 19:37:25

标签: ruby

在编程课程中,我们正在创建一个将句子翻译为Pig Latin的程序。我们被特别告知使用方法,并且所有赋值的给定方法之一是我们可以根据需要重新运行它。后者的正常代码在某种意义上起作用,即如果我们键入"no",它就会退出。但是,如果我们将它放在一个方法中并在while循环结束时调用它,它就像我们输入"yes"一样,而不考虑我们实际键入的内容。

def ask_again()
    puts "Go again? "
    again = gets.chomp
    until again.downcase == "yes" || again.downcase == "no"
        puts "Please answer with \"Yes\" or \"No\""
        again = gets.chomp
    end
    if again == "yes"
        continue = true
    else
        continue = false
    end
end

#Main Program
while continue
    get_input()
    tokenize($input).to_s + "\n" #Ignore these three methods
    scramble_sentence($input)
    ask_again()                  #This is the method I am referring to.
end

2 个答案:

答案 0 :(得分:2)

continue是一个局部变量。当您将其放入方法时,不再可以从“主程序”访问它。最简单的解决方案是让ask_again返回true或false,并将continue设置为ask_again返回的任何内容:

#Main Program
continue = true
while continue
    get_input()
    tokenize($input).to_s + "\n" #Ignore these three methods
    scramble_sentence($input)
    continue = ask_again                  #This is the method I am referring to.
end

更多建议:一般来说,使用全局变量并不是一个好主意,就像你似乎与$input一样。让get_inputtokenize返回字符串而不是让它们修改全局变量$input可能更好。如果我正在编写它,我的“主程序”可能会是这样的:

loop do
    tokenized_input = tokenize(get_input).to_s + "\n"
    scramble_sentence(tokenized_input)
    break unless ask_again
end

答案 1 :(得分:1)

或者您可以将continue设为实例变量(@continue)并添加

@continue = true

while @continue

但最好让ask_again返回t / f。