Reputation: 353
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?
Upvotes: 0
Views: 2846
Reputation: 10138
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
Upvotes: 6
Reputation: 3168
Another approach could be:
x = gets.chomp
x === x.to_i ? "It's an integer" : "It'a a string"
Upvotes: 0