String is a number?

Anton Jenkins | June 22, 2009

I’ve been fishing around to see if Ruby has any way of telling whether a String object contains a valid number. The is_a? method looked like it might be a winner for a little while…

1
2
3
4
5
>> 34.is_a?(Numeric)
=> true

>> "rah rah".is_a?(Numeric)
=> false

So far so good. But my number is going to be stored in a String, and is_a? doesn’t actually look at the value of the String, it just checks its type.

1
2
>> "34".is_a?(Numeric)
=> false

Ah. Fail. String isn’t a numerical class so even though it contains a numerical string, it’s always going to fail that test.

What about to_i?

I found to_i a little too clever for my needs…

1
2
3
4
5
6
7
8
9
>> "34".to_i
=> 34

# All good so far...

>> "34DFDF".to_i
=> 34

# Ah. Fail.

I don’t know why I typed 34DFDF. Sounds like a scary bra size….

Rails Forum to the rescue

Next I found a thread on railsforum.com which showed how to make an is_numeric? method and I decided to take that idea and extend the Object class to include this method on all objects. The idea being you could go :

1
2
3
4
5
6
7
8
>> 34.is_numeric?
=> true

>> "34".is_numeric?
=> true

>> "34DFDF".is_numeric?
=> false

That’s perfect, so let’s write it….

Writing an is_numeric? method

I’m going to extend the Object class with this method so that it’s available everywhere. I’m using this in a rails app so I wrote the following in lib/core_extensions/object.rb

1
2
3
4
5
6
7
8
9
# lib/core_extensions/object.rb

module CoreExtensions::Object
  def is_numeric?
    true if Float(self) rescue false
  end
end

Object.send(:include, CoreExtensions::Object)

What it’s doing is seeing if the Float class can instantiate an instance of itself with the value of object. If object can’t be parsed to a Float then it throws an exception. If an exception is rescued then we know the object can’t be numerical so we return false. Simples.

Now we just need to require our little extension at the end of our environment.rb:

1
2
3
# config/environment.rb

require 'core_extensions/object'

... and we’re ready to go!

1
2
3
4
5
6
7
8
>> 34.is_numeric?
=> true
>> "I'm not a number".is_numeric?
=> false
>> "34".is_numeric?
=> true
>> "34DFDF".is_numeric?
=> false

Perfect.

Why extend Object and not String?

I had a ponder about that and figured it wouldn’t hurt if is_numeric? was called on non strings. By extending Object I can do things such as 34.is_numeric? which isn’t too shoddy. And I’m guessing if something nasty happens the rescue should catch anything bad. But if you can think of a good case for making it a String only method then please feel free to comment.

Also if there’s a better way of checking for numericalness then please post that in the comments. I couldn’t find anything built in to Ruby but I must admit I found that surprising.

comments powered by Disqus