I have a piece of code where I ask the user to input a number as an answer to my question.
I can do to_i
but tricky/garbage inputs would escape through to
to_i is fine but all depends on what You want in case of garbage input. Nil ? the you could use integer(value) and rescue if it's not a integer, the same with Float If you want 693iirum5 to return something else you could parse the string entered and you will need a regex to check the string. Since you ask not to give a regex i won't, perhaps you can clearify what you really want it to return.
The Kernel#Integer method will raise ArgumentError: invalid value for Integer()
if passed an invalid value. The method description says, in part:
[S]trings should be strictly conformed to numeric representation. This behavior is different from that of String#to_i.
In other words, while String#to_i will forcibly cast the value as an integer, Kernel#Integer will instead ensure that the value is already well-formed before casting it.
Integer(gets)
Integer(1)
# => 1
Integer('2')
# => 2
Integer("1foo2\n")
# => ArgumentError: invalid value for Integer(): "1foo2\n"
This will do to validate the input:
Integer(gets) rescue nil
Use input_string.to_i.to_s == input_string
to verify whether the input_string
is an integer or not without regex.
> input_string = "11a12"
> input_string.to_i.to_s == input_string
=> false
> input_string = "11"
> input_string.to_i.to_s == input_string
=> true
> input_string = "11.5"
> input_string.to_i.to_s == input_string
=> false
In answer to camdixon's question, I submit this proposed solution.
Use the accepted answer, but instead of rescue nil
, use rescue false
and wrap your code in a simple if.
print "Integer please: "
user_num=Integer(gets) rescue false
if user_num
# code
end