2015-12-09 39 views
0

我正在開發一個程序,爲用戶提供兩個從0到10的隨機數,供用戶分割,乘,加,或減。如何在用戶輸入「否」時終止此Ruby'while循環?

在每個問題後,用戶有機會通過鍵入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

代替'while'循環,您可以將其交換爲'if'聲明。 'if another!=「no」' –

+0

@philipyoo這個也行得通! Upvoted。 – zappdapper

回答

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 
+0

謝謝,這工作! – zappdapper

相關問題