DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Fred has posted 10 posts at DZone. View Full User Profile

Determine If A String Is Numeric Using Two Regex's In Ruby

08.07.2010
| 957 views |
  • submit to reddit
        Determine if a String is numeric using two regex's
http://www.ruby-forum.com/topic/88507

Re: ruby equivalent PHP function is_numeric?
Posted by Jason Dusek (Guest) on 17.11.2006 18:58  
On 11/17/06, Josselin <josselin@wanadoo.fr> wrote:

> After reading completely my Ruby book, I cannot find a function
> equivalent to the PHP  is_numeric? to test a String

There is no such function, although you can pretty readily use regexes
to do it...

It really is too bad that String.to_f does not throw an exception - or
at least return NaN - when the string is not a number.

> myString.is_numeric?   (check only digits and dot character)

A regex that matches the cases where String.to_f will find a value is
simple to write, and you can create String.numeric? like so:

class String
  def numeric?
    not ( self =~ /^[[:digit:]]+(\.[[:digit:]]+)?([eE][[:digit:]]+)?/ or
          self =~ /^\.[[:digit:]]+([eE][[:digit:]]+)?/ ).nil?
  end
end