How can I check if a value is a number?

Solution 1:

You can use

12.is_a? Numeric

(Numeric will work for integers and floats.)

If it arrives as a string that might contain a representation of a valid number, you could use

class String
  def valid_float?
    true if Float self rescue false
  end
end

and then '12'.valid_float? will return true if you can convert the string to a valid float (e.g. with to_f).

Solution 2:

I usually just use Integer and Float these days.

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

Solution 3:

Just regexp it, it's trivial, and not worth thinking about beyond that:

v =~ /\A[-+]?[0-9]*\.?[0-9]+\Z/

(Fixed as per Justin's comment)

Solution 4:

You can add a:

validates_numericality_of :the_field

in your model.

See: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M002172

Solution 5:

Just convert string twice:

num = '12'
num == num.to_i.to_s 
#=> true 

num = '3re'
num == num.to_i.to_s 
#=> false