PriyankaK
PriyankaK

Reputation: 975

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.

Upvotes: 13

Views: 15759

Answers (5)

Rasmus
Rasmus

Reputation: 345

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

Upvotes: 7

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Use Kernel#Integer

The Kernel#Integer method will raise ArgumentError: invalid value for Integer() if passed an invalid value. The method description says, in part:

[S]trings should be strictly conformed to numeric representation. This behavior is different from that of String#to_i.

In other words, while String#to_i will forcibly cast the value as an integer, Kernel#Integer will instead ensure that the value is already well-formed before casting it.

Examples Simulating Behavior of Integer(gets)

Integer(1)
# => 1

Integer('2')
# => 2

Integer("1foo2\n")
# => ArgumentError: invalid value for Integer(): "1foo2\n"

Upvotes: 2

peter
peter

Reputation: 42182

to_i is fine but all depends on what You want in case of garbage input. Nil ? the you could use integer(value) and rescue if it's not a integer, the same with Float If you want 693iirum5 to return something else you could parse the string entered and you will need a regex to check the string. Since you ask not to give a regex i won't, perhaps you can clearify what you really want it to return.

Upvotes: 0

Prakash Murthy
Prakash Murthy

Reputation: 13057

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   

Upvotes: 3

sawa
sawa

Reputation: 168071

This will do to validate the input:

Integer(gets) rescue nil

Upvotes: 18

Related Questions