5.15. Implicit and Explicit Numeric ConversionThe 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 = MyClass.new 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; Array.new can take an integer, but what happens if we give it a MyClass object instead? m = MyClass.new a = Array.new(m) # [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." |