How to check if user input is a number

eus*_*ass 1 ruby

I'm making this small program and I want to check if the user entered an Integer number, if he did it the program will continue but if the user enters a string I want to the program to ask the user to enter an Integer until he does it, here's my code snippet:

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
Run Code Online (Sandbox Code Playgroud)

Hor*_*cio 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 
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)