sepiroth sepiroth - 1 year ago 82
Ruby Question

elegant way to check if a string inputed by user is an integer in ruby?

I'm trying to validate that the input a user gives my program via

is an integer.
does not work, as far as i can tell, because
gets a string from the user, so it will always return false even if the user enters an valid integer (in string form). One would think I could simply use
on the input and be done with it, but that raises another issue -
results in
. So if I relied on
to solve my problems, anything starting with numbers will work.

How do I cleanly validate that the value is an integer only, and not a combination of numbers and letters? Or do I need to resort to regex for this?

Answer Source

How about s.to_i.to_s == s? I'd prefer regex however.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download