How to cleanly verify if the user input is an integer in Ruby? How to cleanly verify if the user input is an integer in Ruby? ruby ruby

How to cleanly verify if the user input is an integer in Ruby?


This will do to validate the input:

Integer(gets) rescue nil


In answer to camdixon's question, I submit this proposed solution.

Use the accepted answer, but instead of rescue nil, use rescue false and wrap your code in a simple if.

Example

print "Integer please: " user_num=Integer(gets) rescue false if user_num     # code end


Use input_string.to_i.to_s == input_string to verify whether the input_string is an integer or not without regex.

> input_string = "11a12"> input_string.to_i.to_s == input_string=> false> input_string = "11"> input_string.to_i.to_s == input_string=> true> input_string = "11.5"> input_string.to_i.to_s == input_string=> false