在编程课程中,我们正在创建一个将句子翻译为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
答案 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_input
和tokenize
返回字符串而不是让它们修改全局变量$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。