Type Casting and Conversions

  • published on September 17th, 2008

    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_s and to_i are very commonly used to translate between different objects.

    PHP Ruby
    convert to integer (int) "3"; "3".to_i
    convert to float (float) "1.2"; "1.2".to_f
    convert to string (string) 1; 1.to_s
    convert 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, and String.

    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.

    Integer will honor base indicators such as (0, 0x, and 0b), but String#to_i will not. If Integer cannot convert an object it will throw an ArgumentError.

    Ruby

    "0x12".to_i    # => 0
    Integer("0x12")  # => 18
     
    "a".to_i       # => 0
    Integer("a")   # => ArgumentError: invalid value for Integer: "a"

    Float will throw a TypeError if you attempt to convert nil to a float. If it cannot convert an object it will throw an ArgumentError.

    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"

    String works pretty much the same as the to_s method, and is basically just calling the object’s to_s method.

    Array will attempt to call object.to_ary, and then object.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 rescue along with a value that we want to assign when an exception is raised during the conversion.

1 comment

Post a comment


We welcome your participation but please note we reserve the right to remove any comments that we think are not relevant or do not contribute to the discussion.