kushtrimh kushtrimh - 3 months ago 17
Ruby Question

How to check if user input is a number

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

Answer

I think that your error is the to_i after gets.chomps.

to_i returns the first number(s) at the begining of a string or 0, so you allways get a number (0 or another number). Here are some examples:

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 

I wrote this code, which works for me:

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