2
votes

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
4
And? Is it not working? If so what is it doing?NathanOliver
It doesn't ask for the user input again, even if I enter something like "yasdga" when it asks for the input it still just pass, it doesn't ask again for the input even if I enter a string.kushtrimh
Well, you first convert it to a number, then ask if it is a number. Of course it is, you just converted it to one.Jörg W Mittag
"007 likes martinis shaken".to_i #=> 7. "Goldfinger prefers them stirred.".to_i #=> 0.Cary Swoveland
Two ways to determine if a string str represents a Fixnum and if it does, return the Fixnum; else return nil: 1) Use a regex with anchors: def intify(str); x = str[/^-?\d+$/]; x ? x.to_i : nil; end.intify("007 likes martinis") #=> nil; intify("-33") #=> -33. 2) Use Kernel::Integer(ruby-doc.org/core-2.2.0/Kernel.html#method-i-Integer): def intify(str); Integer(str) rescue nil; end. intify("007 likes martinit") #=> nil; intify("-33") #=> -33.Cary Swoveland

4 Answers

5
votes

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 ArgumentError
  print "Please enter an integer number:"
  retry
end
print user_age.to_s
1
votes
begin
  p "How old are you:"
  user_age = Integer(gets.chomp)
rescue
  p "Please enter an integer number:"
  retry
end
print user_age
1
votes

Maybe instead you could also use:

until user_age.to_i.to_s == user_age
  puts "Please enter your age as a number"
  user_age = gets.chomp
end
0
votes
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