问题
I have the string "08"
and I like to know if this string is numeric. How can I do it in Rails 3.1?
回答1:
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
回答2:
You can use a regular expression:
str = "08"
if str =~ /^-?(\d+(\.\d+)?|\.\d+)$/
# string is numeric
else
# string is not
end
回答3:
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]/
.
来源:https://stackoverflow.com/questions/9469587/how-can-i-see-if-the-string-is-numeric