1 min read

Is it an Integer?

Casting strings to integers without exceptions
Is it an Integer?
Photo by Nick Hillier / Unsplash

Filed under 'I should have known this already'...

I want to cast a string to an integer. Only it might not actually be an integer so I have a couple of options:

  1. my_string.to_i
  2. Integer(my_string)

So the first is problematic because to_i is permissive. If the string isn't parseable as an integer, it'll return zero.

The second is pain because it's restrictive and will throw an ArgumentError if it's not castable and exception handling is slow.

But I can do this:

my_string = 'Billy'
Integer(my_string, exception: false)
#=> nil

So I get a nil for a non-castable string or the integer value back if it castable, all without exceptions.