Punya
Punya

Reputation: 353

Checking if number is an integer in ruby using gets.chomp.to_i

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

Answers (3)

Ronan Boiteau
Ronan Boiteau

Reputation: 10138

Your problem

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.

Solution

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

Sagar Pandya
Sagar Pandya

Reputation: 9497

You can use a regex:

boolean = gets.match?(/\A\d+\n\z/)

Upvotes: 2

Subash
Subash

Reputation: 3168

Another approach could be:

x = gets.chomp
x === x.to_i ? "It's an integer" : "It'a a string"

Upvotes: 0

Related Questions