如何在Ruby中满足某些条件之前提示用户输入?

时间:2017-08-07 11:14:03

标签: ruby

此程序不断显示错误消息,并且不会突破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"

我做错了什么?

1 个答案:

答案 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"