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?

0

1 Answer 1

29

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.

Sign up to request clarification or add additional context in comments.

2 Comments

As of Ruby 2.6.0, the rescue nil can be avoided by using Integer("one", exception: false). See my answer here: stackoverflow.com/a/54022892/4469336
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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.