Ruby: Check if a String is a valid number

Wed 22 May 2013 by Pol O'Riain

A problem I often meet in Ruby development, and programming as a whole, is determining if a string is a valid number. I’ve seen many approaches to this including a regex;

v =~ /^[-+]?[0-9]*\.?[0-9]+$/

Or calling is_a?

irb(main):005:0> 1.is_a? Numeric
=> true
irb(main):006:0> 1.1.is_a? Numeric
=> true
irb(main):007:0> 'abc'.is_a? Numeric
=> false

But I’ve come to start using the built in Integer and Float methods.

1.9.2p320 :001 > foo = "343"
 => "343"
1.9.2p320 :003 > goo = "fg5"
 => "fg5"

1.9.2p320 :002 > Integer(foo) rescue nil
 => 343
1.9.2p320 :004 > Integer(goo) rescue nil
 => nil

1.9.2p320 :005 > Float(foo) rescue nil
 => 343.0
1.9.2p320 :006 > Float(goo) rescue nil
 => nil

This allows me to easily specify a default value on a fail. For example if I wanted the value to always be at least 1.

1.9.2p320 :003 > the_string = "abc"
 => "abc"
1.9.2p320 :006 > Float(the_string) rescue 1
 => 1

Of course if you are using Rails, as many likely are, you can simply use the validations provided.

validates_numericality_of :the_field

As always with Ruby (and Rails) there are many different approaches any problem so choose whichever best suits what you want to accomplish.