如何检查用户输入是否为数字

时间:2015-07-14 15:18:56

标签: ruby

我正在制作这个小程序,我想检查用户是否输入了整数,如果他这样做,程序将继续,但如果用户输入字符串我想要程序要求用户输入一个整数,直到他这样做,这是我的代码片段:

print "How old are you:"
    user_age = gets.chomp.to_i
    if user_age.is_a? String
        puts "Please enter an integer number:"
        user_age = gets.chomp.to_i
        until user_age.is_a? Numeric
            puts "Please enter an integer number:"
            user_age = gets.chomp.to_i
            break if user_age.is_a? Numeric
        end
    end

4 个答案:

答案 0 :(得分:5)

我认为您的错误是to_i之后的gets.chomps

to_i返回字符串开头的第一个数字或0,所以你总是得到一个数字(0或另一个数字)。以下是一些例子:

2.2.1 :001 > "12".to_i
 => 12
2.2.1 :002 > "12aaa".to_i
 => 12 
2.2.1 :003 > "aaa12aaa".to_i
 => 0 
2.2.1 :004 > "aaaaaa".to_i
 => 0 

我写了这段代码,对我有用:

print "How old are you:"
begin
  user_age = gets.chomp
  user_age = Integer(user_age)
rescue ArgumentError
  print "Please enter an integer number:"
  retry
end
print user_age.to_s

答案 1 :(得分:1)

begin
  p "How old are you:"
  user_age = Integer(gets.chomp)
rescue
  p "Please enter an integer number:"
  retry
end
print user_age

答案 2 :(得分:1)

也许您也可以使用:

until user_age.to_i.to_s == user_age
  puts "Please enter your age as a number"
  user_age = gets.chomp
end

答案 3 :(得分:0)

print "How old are you: "
user_age = gets.chomp

while true
    if user_age.to_i.to_s == user_age
        print "Your age is #{user_age}"
        break
    else
        print "please enter your age in number "
        user_age = gets.chomp
    end
end