sepiroth sepiroth - 4 months ago 21
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

gets
is an integer.
is_a?(Integer)
does not work, as far as i can tell, because
gets
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
to_i
on the input and be done with it, but that raises another issue -
"75akjfas".to_i
results in
75
. So if I relied on
to_i
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

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