Yup, thanks... just noticed that about ArgumentError. I'm actually
catching both now, that way nils work gracefully. Although
one could have an argument about whether nil represents
a number or not. :)
-glenn
Jason King wrote:
Actually, negatives and scientific both currently return true with
Kevin's example. Unfortunately, so do a lot of others :)
some_number = 'any string with a number like 4 in it will be true
but not a number'
And yes, as you fix those false positives, you begin introducing the
false negatives Glenn's talking about :)
Only comment I have for you *Glenn* is that I can't see any reason for
the conditional, and it's an ArgumentError not a TypeError that's
thrown. I think your method becomes simply:
def represents_number?(s)
Float(s)
rescue ArgumentError
return false
end
On Jan 22, 2010, at 12:01 PM, Glenn Little wrote:
Negative numbers, scientific notation, any other oddball cases
I'm not thinking of. They'd all be reasonably easy to cobble in,
but it's the "I'm not thinking of" part that I was trying to avoid.
-glenn
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]
<mailto:[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] <mailto:[email protected]>
http://groups.google.com/group/sdruby
--
SD Ruby mailing list
[email protected] <mailto:[email protected]>
http://groups.google.com/group/sdruby
--
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby
--
SD Ruby mailing list
[email protected]
http://groups.google.com/group/sdruby