I can convert an object to an integer with to_i
. How can I get it to not convert if the input is not a number?
In python I would do this:
h=input("Number: ")
try:
h=int(h)
except ValueError:
print("Please enter numbers!")
So I tried this in ruby:
print "Number: "
h=gets.chomp
try(h.to_i)
print(h)
end
but it prints the input even if I enter letters, so this means I am doing it wrong. What is the correct Ruby way of doing this?
Reading ruby docs for to_i
Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. This method never raises an exception when base is valid.
What you want in your case (to map the Python behavior) is:
begin
Integer(gets)
rescue ArgumentError
puts "Please enter numbers!"
end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.