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
代替'while'循環,您可以將其交換爲'if'聲明。 'if another!=「no」' –
@philipyoo這個也行得通! Upvoted。 – zappdapper