如何使用布尔值进行用户输入验证

时间:2020-04-23 22:38:06

标签: ruby if-statement boolean

这是我的代码的一部分,˚语句的第一部分有效,但是我希望显示一条单独的消息,以用于非数字输入,例如“ $boo”,“ ten” ,“ idk”)。

puts "Candy Sold: "
candy_sold = gets.chomp.to_i
 until candy_sold >= 0 
  if candy_sold < 0
    puts "Please enter a positive number:"
    candy_sold = gets.chomp.to_i
  elsif candy_sold.class == String      # This is where the issue is
    puts "Please enter a positive number:"
    candy_sold = gets.chomp.to_i
  end
 end

2 个答案:

答案 0 :(得分:0)

如果您检查已转换的数字,则无法确定其最初是否为有效格式。您必须以某种方式与初始输入进行比较。

解决方案之一:

ask_for_amount = true

while ask_for_amount
  candy_number_input = gets.chomp.strip
  candy_sold = candy_number_input.to_i

  if candy_number_input != candy_sold.to_s
    puts "Please enter a valid positive number:"
  elsif candy_sold < 0
    puts "Please enter a positive number:"
  else
    ask_for_amount = false
  end
end

答案 1 :(得分:0)

如果我对您的问题理解正确,那么您只想允许使用正数。在这种情况下,可以将cover?方法与范围一起使用。

puts "Candy Sold: "
candy_sold = gets.chomp
until ('0'..'9').cover? candy_sold
  puts "Please enter a positive number"
  candy_sold = gets.chomp
end

Candy Sold: 
> Hello
=> Please enter a positive number
> -97
=> Please enter a positive number
> -0
=> Please enter a positive number
> 1
=> nil