Guilherme Costa
Guilherme Costa

Reputation: 1329

How can I see if the string is numeric?

I have the string "08" and I like to know if this string is numeric. How can I do it in Rails 3.1?

Upvotes: 1

Views: 1298

Answers (3)

Josh
Josh

Reputation: 5721

If you are wanting to validate user input it would be just as simple to only allow them to input numbers with something like validates_format_of :string, :with => /[0-9]/.

Upvotes: 0

Alberto Santini
Alberto Santini

Reputation: 6564

Another way to do this is to leave it up to ruby to determine it:

begin
    Float(string)
    # String is numeric
rescue ArgumentError, TypeError
    # String is not numeric
end

Upvotes: 4

robbrit
robbrit

Reputation: 17960

You can use a regular expression:

str = "08"
if str =~ /^-?(\d+(\.\d+)?|\.\d+)$/
  # string is numeric
else
  # string is not
end

Upvotes: 3

Related Questions