I am planning to check if a given input is an integer. gets.chomp
gets input as a string, and I convert it into an integer using to_i
. If I input abcd
and check using class
or is_a(Integer)
, it always says it's an integer.
x = gets.chomp.to_i
if x.is_a?(Integer)
puts "It's an integer"
else
puts "It's a string"
end
How can I check whether the input is an integer or a string?
Since you're using .to_i
to convert your input to an integer, x.is_a?(Integer)
is always true
, even when you have a string that does not contain any digit. See this answer for more information about .to_i
's behavior.
Convert your input with Integer()
instead of .to_i
.
Integer()
throws an exception when it cannot convert your input to an integer, so you can do the following:
input = gets.chomp
x = Integer(input) rescue false
if x
puts "It's an integer"
else
puts "It's a string"
end
您可以使用正则表达式:
boolean = gets.match?(/\A\d+\n\z/)
Another approach could be:
x = gets.chomp
x === x.to_i ? "It's an integer" : "It'a a string"
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.