11

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?

Community
  • 1
  • 1
MxLDevs
  • 19,048
  • 36
  • 123
  • 194

1 Answers1

28

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.

Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
  • 3
    As of Ruby 2.6.0, the `rescue nil` can be avoided by using `Integer("one", exception: false)`. See my answer here: https://stackoverflow.com/a/54022892/4469336 – Timitry Jan 03 '19 at 13:08
  • 1
    Old answer but I just stumbled across it and figured I'd point out that `'09'` doesn't have to error, at least anymore: `Integer()` takes an optional second positional argument for `base`, so `Integer('09', 10)` would give you `9` – Ben Saufley Jun 15 '22 at 15:16