Section 5.16. Coercing Numeric Values

5.15. Implicit and Explicit Numeric Conversion

The new Rubyist is often confused that there are methods named to_i and to_int (and by analogy, to_f and to_flt, as well as others). In general, explicit conversion is done using the "short name" and implicit conversion using the "long name."

What does this mean? First, most classes define explicit convertors but not implicit; to_int and to_flt are not defined anywhere in the core that I am aware of.

Second, your own classes will tend to define implicit convertors, but you will not usually call them manually (unless you are writing "client" code or library-oriented code that tries to play well with the outside world).

The following code is a contrived example. The class MyClass as defined in this example returns constants from to_i and to_int. This is nonsensical behavior, but it illustrates a point:

class MyClass   def to_i     3   end   def to_int     5   end end

If we want to convert a MyClass object explicitly to an integer, we can call to_i:

m = x = m.to_i        # 3

But the to_int method gets called implicitly ("behind our backs") when we pass in a MyClass object to something that expects an integer. For example, suppose that we want to create an array with an initial number of values; can take an integer, but what happens if we give it a MyClass object instead?

m = a =   # [nil,nil,nil,nil,nil]

As we see, the new method was smart enough to call to_int and thus create an array with five entries.

For more explanation in a different context (strings), see the section 2.16, "Implicit and Explicit Conversion." See also the following section 5.16 "Coercing Numeric Values."

The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: