As an obscure case, Ruby supports the '_' as a thousands separator. There might be others.
>> "10_000".to_i => 10000 On Jan 22, 2010, at 11:43 AM, Kevin Clark wrote: > /\d+(\.\d+)?/ =~ some_number > > Doesn't do what you need? Is there an obvious edge case I'm missing? A > number is one or more digits, optionally followed by a . and one or > more digits. > > =~ will give you nil if it doesn't match, or the index of the match if > it does (which you can just use as non false). > > On Fri, Jan 22, 2010 at 11:35 AM, Glenn Little <[email protected]> wrote: >> I'm looking for a simple way to check if a string really represents >> a number in ruby/rails. I figured there would be a String.is_numeric? >> but haven't found anything. >> >> I've seen suggestions for roll-your-own functions the best of which >> appears to be something like (verbosely): >> >> def represents_number?(s) >> begin >> if Float(s) >> return true >> else >> return false >> end >> rescue >> return false >> end >> end >> >> This relies on the fact that Float() throws an exception if it >> gets a string that it can't convert. >> >> The issue I have with this is that it feels a little hinky in >> that it's relying on Float throwing an exception. Maybe that's >> okay, but it feels just a shade side-effecty. >> >> The other option is to craft a regexp, which would be tough >> if I *really* wanted to be thorough. >> >> Am I missing any simpler options? >> >> Thanks... >> >> -glenn >> >> >> -- >> SD Ruby mailing list >> [email protected] >> http://groups.google.com/group/sdruby > > > > -- > Kevin Clark > http://glu.ttono.us > > -- > SD Ruby mailing list > [email protected] > http://groups.google.com/group/sdruby -- SD Ruby mailing list [email protected] http://groups.google.com/group/sdruby
