Type Conversions in Ruby: The "Right" Way? -


I am trying to decide whether Ruby has a string number. This is my code

  whatAmI = "32.3a22" puts "it's always false" + string (whatAmI.is_a? (Fixation)); IsNum = false; Start float (whatAmI) isNum = true; Rescue exception = & gt; E puts "What does Ruby say?" + E = No. = Incorrect; End Points Hanam  

I realize that I can do this with a RegEx, but Is there any standard way to do this that I am missing? saw a can_convert? Method, but I do not think so

Is there any way to add Can-convert? Method for all strings? I think it is possible in Ruby. I also understand that it can be totally unnecessary ...

Edit does not work in ways to_f, because they never throw exceptions, but only Come back to 0 if it is not working.

You've got the right idea. It can be done in a slightly more complex way, however:

  isNum = float (whatAmI) Rescue zero  

Inlining "rescue" It's great fun if you put it in the middle of more stuff, so protect that part, such as:

  if (isNum = Float (whatAmI) Rescue zero) & amp; Amp; IsNum & gt; 20 ...  

Comments