当用户输入" no&#34 ;?时,如何终止这个Ruby`while`循环?

时间:2015-12-09 00:31:48

标签: ruby loops

我正在开发一个程序,为用户提供两个随机数,范围从0到10,供用户进行分割,乘法,加法或减法。

在每个问题之后,用户都有机会通过键入no来停止该程序。

我正在使用while循环,但是当用户输入no时,我无法终止循环。如何让程序正确响应用户输入?

def math_num
  nums = [num_1 = rand(1..10), num_2 = rand(1..10), operator = ["+", "-", "/", "*"].sample]
  problem = "What is #{num_1} #{operator} #{num_2}?"
  puts problem

  $input = gets.to_i
  $answer = num_1.send(operator, num_2)

  puts $input == $answer ? "You answered #{$input}, and the answer is #{$answer}! You are correct!" : "The answer is #{$answer}, not #{$input}! You are incorrect!"   

  def try_again
    puts "Would you like to do another question?"
    another = gets.chomp.to_s
    while another != "no"
        math_num
    end
  end

  try_again 

end

math_num

1 个答案:

答案 0 :(得分:2)

好吧,你这样做的方式是你得到一个无限循环,因为another变量的值没有在while循环中更新。

请改为尝试:

def math_num
    while true
        nums = [num_1 = rand(1..10), num_2 = rand(1..10), operator = ["+", "-", "/","*"].sample]
        problem = "What is #{num_1} #{operator} #{num_2}?"
        puts problem

        $input = gets.to_i
        $answer = num_1.send(operator, num_2)

        puts $input == $answer ? "You answered #{$input}, and the answer is #{$answer}! You are correct!" : "The answer is #{$answer}, not #{$input}! You are incorrect!"   

        puts "Would you like to do another question?"
        another = gets.chomp.to_s
        if another == "no"
            break
        end
    end
end

math_num