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_i
. For example, if a user inputs 693iirum5
as an answer then #to_i would strip it to 693
.
Please suggest a function, not a regular expression. Thanks in advance for replying.
This will do to validate the input:
Integer(gets) rescue nil
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
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