'Ruby: checking if a string can be converted to an integer [duplicate]

Possible Duplicate:
Test if a string is basically an integer in quotes using Ruby?

"1"
"one"

The first string is a number, and I can just say to_i to get an integer.
The second string is also a number, but I can't directly call to_i to get the desired number.

How do I check whether I can successfully convert using to_i or not?



Solution 1:[1]

There's an Integer method that unlike to_i will raise an exception if it can't convert:

>> Integer("1")
=> 1
>> Integer("one")
ArgumentError: invalid value for Integer(): "one"

If you don't want to raise an exception since Ruby 2.6 you can do this:

Integer("one", exception: false)

If your string can be converted you'll get the integer, otherwise nil.

The Integer method is the most comprehensive check I know of in Ruby (e.g. "09" won't convert because the leading zero makes it octal and 9 is an invalid digit). Covering all these cases with regular expressions is going to be a nightmare.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1