ruby - How to check if user input is a number -


i'm making small program , want check if user entered integer number, if did program continue if user enters string want program ask user enter integer until it, here's code snippet:

print "how old you:"     user_age = gets.chomp.to_i     if user_age.is_a? string         puts "please enter integer number:"         user_age = gets.chomp.to_i         until user_age.is_a? numeric             puts "please enter integer number:"             user_age = gets.chomp.to_i             break if user_age.is_a? numeric         end     end 

i think error to_i after gets.chomps.

to_i returns first number(s) @ begining of string or 0, allways number (0 or number). here 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 code, works me:

print "how old you:" begin   user_age = gets.chomp   user_age = integer(user_age) rescue   print "please enter integer number:"   retry end print user_age.to_s 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -