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 ...

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.