-1

In programming class, we are creating a program to translate a sentence to Pig Latin. We are specifically told to use methods, and one of the given ones for all assignments is that we could re-run it as many times as we want to. The normal code for the latter works in the sense that if we type "no", it exits. However, if we put it in a method and call it at the end of the while loop, it acts as if we typed "yes", with no regard to what we actually typed.

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
4

2 回答 2

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
于 2013-11-08T19:51:00.660 回答
1

或者您可以创建continue一个实例变量 ( @continue) 并添加

@continue = true

while @continue

但最好有ask_again回报t/f。

于 2013-11-08T19:57:02.273 回答