Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 961
Tony Stark Avatar asked Dec 12 '22 12:12

Tony Stark


1 Answers

print "Enter an integer (or try to sneak by something other): "
puts Integer(gets) rescue puts "Hey, that's not an integer!"
like image 142
steenslag Avatar answered Jun 08 '23 10:06

steenslag