I am trying to decide if a string is a number in Ruby. This is my code
whatAmI = "32.3a22"
puts "This is always false " + String(whatAmI.is_a?(Fixnum));
isNum = false;
begin
Float(whatAmI)
isNum = true;
rescue Exception => e
puts "What does Ruby say? " + e
isNum = false;
end
puts isNum
I realize that I can do it with a RegEx, but is there any standard way to do it that I'm missing? I've seen a can_convert? method, but I don't seem to have it.
Is there a way to add a can_convert? method to all Strings? I understand that it's possible in Ruby. I also understand that this may be totally unecessary...
Edit The to_f methods do not work, as they never throw an Exception but rather just return 0 if it doesn't work out.
You've got the right idea. It can be done a little more compactly, though:
isNum = Float(whatAmI) rescue nil
Inlining "rescue" is great fun. Parenthesize the part you're rescuing if you put it in the middle of more stuff, like:
if (isNum = Float(whatAmI) rescue nil) && isNum > 20
...
This might sound overly critical, but based on your description, you're almost certainly doing something "wrong"... Why would you need to check whether a String is a valid representation of a Float
but not actually convert the String?
This is just a hunch, but it may be useful to describe what you're trying to accomplish. There's probably a "better" way.
For example, you might want to insert the String into a database and put together an sql statement using string concatenation. It would be preferable to convert to a Float and use prepared statements.
If you just need to inspect the "shape" of the string, it would be preferable to use a regular expression, because, as dylan pointed out, a Float can be represented in any number of ways that may or may not be appropriate.
You may also have to deal with international input, in Europe, a comma is used instead of a period as decimal seperator, yet Ruby Floats have to use the (.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With