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?
print "Enter an integer (or try to sneak by something other): "
puts Integer(gets) rescue puts "Hey, that's not an integer!"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With