Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a piece of code where I ask the user to input a number as an answer to my question. I can do to_i but tricky/garbage inputs would escape through to_i. For example, if a user inputs 693iirum5 as an answer then #to_i would strip it to 693.

Please suggest a function, not a regular expression. Thanks in advance for replying.

like image 515
PriyankaK Avatar asked Feb 15 '13 17:02

PriyankaK


2 Answers

This will do to validate the input:

Integer(gets) rescue nil
like image 91
sawa Avatar answered Oct 23 '22 07:10

sawa


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
like image 44
Rasmus Avatar answered Oct 23 '22 08:10

Rasmus