如何查看字符串是否为数字?

我有字符串"08" ,我想知道这个字符串是否是数字。 我怎么能在Rails 3.1中做到这一点?

另一种方法是将它留给ruby来确定它:

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

您可以使用正则表达式:

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

如果您想要validation用户输入,那么只允许他们输入类似validates_format_of :string, :with => /[0-9]/数字就好了。