检查用户输入是否在Ruby中的某个范围内

时间:2013-12-17 01:52:42

标签: ruby if-statement range

如果用户输入除数字以外的任何数字,除了数字范围为1 - 32之外的任何数字,我还需要它再次请求输入。

当我在1..32

中使用cut_number时,它会给我一个错误
def cut_the_deck
  puts "You get to cut the deck to make it even more random!"
  puts "Type a number between 1 and 32. That's where the deck will be cut!"
    cut_number = gets.chomp
    cut_number = cut_number.to_i
      if cut_number in 1..32
        puts "Number in range"
      else
        puts "Number NOT in range"
        cut_the_deck
      end
end

2 个答案:

答案 0 :(得分:3)

使用between?

if cut_number.between?(1,32) #=> true or false

答案 1 :(得分:2)

或者你可以这样做:

if (1..32).include?(cut_number)