Type Conversions in Ruby: The β€œRight” Way?

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 understand that I can do this with RegEx, but is there a standard way to do this that I am missing? Have I seen can_convert? method, but I don’t have it.

Is there any way to add can_convert? method for all lines? I understand that this is possible in Ruby. I also understand that this can be completely unnecessary ...

Change The to_f methods do not work, because they never throw an exception, but simply return 0 if this does not work.

+6
types ruby
source share
3 answers

You have the right idea. This can be done a little more compactly:

 isNum = Float(whatAmI) rescue nil 

Investing "salvation" is great fun. Parenthesize the part that you will save if you put it in the middle of more things, for example:

 if (isNum = Float(whatAmI) rescue nil) && isNum > 20 ... 
+9
source share

This may seem overly critical, but based on your description, you will almost certainly do something β€œwrong” ... Why do you need to check if String is a valid representation of Float , but String is not actually converted?

This is just a hunch, but it may be helpful to describe what you are trying to accomplish. This is probably the "best" way.

For example, you might need to insert a String into a database and compile a sql statement using string concatenation. It would be preferable to convert to Float and use prepared statements.

If you just need to check the "shape" of the string, it would be preferable to use a regular expression, because, as Dylan pointed out, Float can be represented in any number of ways, which may or may not be necessary.

You will also have to deal with international input, in Europe a comma is used instead of a period as a decimal separator, but Ruby Floats should use (.).

+4
source share

I don't know about the can_convert method, but usually a class will define methods like to_s , to_i , to_hash , etc. These methods return another representation of the object, for example, the to_s method returns a string representation of the object.

As for the actual conversion, I'm sure someone else can answer this better than me.

In another note, if you are wondering if you can add a method to all lines, you can. Just open the String class and add it!

 class String def can_convert? ... end end 

Edit: Lines containing exponential notation are supported by to_f .

 >> "6.02e23".to_f => 6.02e+23 
+3
source share

All Articles