此程序不断显示错误消息,并且不会突破while
语句:
puts "rate it"
rating = gets.chomp.to_i
while rating != 1..4
puts "error it has to be comprised between 1 and 4"
puts "rate it"
rating = gets.chomp.to_i
break if rating == 1..4
end
puts "rated"
我做错了什么?
答案 0 :(得分:4)
您需要修改检查rating
范围的方式:rating == 1..4
不会检查rating
是否介于1和4之间。它会检查rating
是范围对象 1..4
。
所以,将while rating != 1..4
更改为while !(1..4).member?(rating)
。另外,在break
语句中进行类似的更改。
虽然我们正在处理它,但您也可以删除break
语句,因为while
条件会在rating
具有正确值时中断循环。< / p>
正如Stefan在评论中指出的那样,代码中存在相当多的重复,可以轻松删除并使用between(1, 4)
,因为循环退出条件更具可读性。
这是更新后的代码:
loop do
puts "rate it"
rating = gets.chomp.to_i
break if rating.between?(1, 4)
puts "error it has to be comprised between 1 and 4"
end
puts "rated"