Type Casting and Conversions
-
In the Rails for PHP Developers book we mention that Ruby objects have conversion methods to translate between different object types.
Object Conversion Methods
Methods such as
to_sandto_iare very commonly used to translate between different objects.PHP Ruby convert to integer (int) "3";"3".to_iconvert to float (float) "1.2";"1.2".to_fconvert to string (string) 1;1.to_sconvert to array (array) "test";[*"test"]Kernel Module Conversion Methods
This isn’t the only way to convert object types in Ruby. We can use Kernel module conversion methods as well. These methods include
Array,Float,Integer, andString.PHP Ruby convert to integer (int) "3";Integer("3")convert to float (float) "1.2";Float("1.2")convert to string (string) 1;String(1)convert to array (array) "test";Array("test")The Differences
These methods perform similar actions to the instance conversion methods, but have some subtle differences.
Integerwill honor base indicators such as (0, 0x, and 0b), butString#to_iwill not. If Integer cannot convert an object it will throw anArgumentError.Ruby
"0x12".to_i # => 0 Integer("0x12") # => 18 "a".to_i # => 0 Integer("a") # => ArgumentError: invalid value for Integer: "a"
Floatwill throw aTypeErrorif you attempt to convert nil to a float. If it cannot convert an object it will throw anArgumentError.Ruby
nil.to_f # => 0.0 Float(nil) # => TypeError: can't convert nil into Float "a".to_i # => 0.0 Float("a") # => ArgumentError: invalid value for Float(): "a"
Stringworks pretty much the same as theto_smethod, and is basically just calling the object’sto_smethod.Arraywill attempt to callobject.to_ary, and thenobject.to_a. If the object doesn’t respond to either, it will create a single element array with the object.Tips
The great thing about any Ruby errors we might get while attempting to convert types is that they’re
exceptions. This means that we can easily handle them, and set a default value if any conversion doesn’t work as expected.Ruby
my_var = ["hello"] my_var.to_i rescue 0 # => 0 my_var = "a" Float(my_var) rescue 0.0 # => 0.0
In this example, we’ve used an inline
rescuealong with a value that we want to assign when an exception is raised during the conversion.


1 comment
pingback by Rails for PHP Developers - Empty Variables 23 Sep 08
[...] Ruby code, we typically know when we’re working with numbers, or we can cast to them. We can then simply do something like these [...]
Post a comment