Test if string is a number in Ruby on Rails

Jamie Buchanan picture Jamie Buchanan · Apr 14, 2011 · Viewed 114k times · Source

I have the following in my application controller:

def is_number?(object)
  true if Float(object) rescue false
end

and the following condition in my controller:

if mystring.is_number?

end

The condition is throwing an undefined method error. I'm guessing I've defined is_number in the wrong place...?

Answer

Jakob S picture Jakob S · Apr 14, 2011

Create is_number? Method.

Create a helper method:

def is_number? string
  true if Float(string) rescue false
end

And then call it like this:

my_string = '12.34'

is_number?( my_string )
# => true

Extend String Class.

If you want to be able to call is_number? directly on the string instead of passing it as a param to your helper function, then you need to define is_number? as an extension of the String class, like so:

class String
  def is_number?
    true if Float(self) rescue false
  end
end

And then you can call it with:

my_string.is_number?
# => true