I'm making this small program and I want to check if the user entered an Integer number, if he did it the program will continue but if the user enters a string I want to the program to ask the user to enter an Integer until he does it, here's my code snippet:
print "How old are you:"
user_age = gets.chomp.to_i
if user_age.is_a? String
puts "Please enter an integer number:"
user_age = gets.chomp.to_i
until user_age.is_a? Numeric
puts "Please enter an integer number:"
user_age = gets.chomp.to_i
break if user_age.is_a? Numeric
end
end
"007 likes martinis shaken".to_i #=> 7
."Goldfinger prefers them stirred.".to_i #=> 0
. – Cary Swovelandstr
represents aFixnum
and if it does, return theFixnum
; else returnnil
: 1) Use a regex with anchors:def intify(str); x = str[/^-?\d+$/]; x ? x.to_i : nil; end
.intify("007 likes martinis") #=> nil; intify("-33") #=> -33
. 2) Use Kernel::Integer(ruby-doc.org/core-2.2.0/Kernel.html#method-i-Integer):def intify(str); Integer(str) rescue nil; end
.intify("007 likes martinit") #=> nil; intify("-33") #=> -33
. – Cary Swoveland