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:
Inlining ‘rescue’ is great fun. Parenthesize the part you’re rescuing if you put it in the middle of more stuff, like: