当用户输入时,如何终止这个Ruby`while`循环;否;?
我正在开发一个程序,它给用户提供两个从0到10的随机数,供用户进行除法、乘法、加法或减法 在每个问题之后,用户都有机会通过键入当用户输入时,如何终止这个Ruby`while`循环;否;?,ruby,loops,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 #
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
好的,你这样做的方式就是得到一个无限循环,因为
另一个变量的值在循环中没有被更新
请尝试以下方法:
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
您可以将其替换为if
语句,而不是while
循环<代码>如果是另一个!=“不”
@philipyoo这也行!向上投票。