Reputation: 1329
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
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
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
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