From: Daniel Schierbeck Date: 2006-07-29T03:45:05+09:00 Subject: Re: Symbols are your friends Aleks Kissinger wrote: > If an object _can_ be represented as an integer in some cases (e.g. a > string, which could be set to something like "12"), it implements > to_i. > > If an object _is_ a natural representation of an integer, (like roman > numerals, as the example the Pickaxe gives), it implements to_int. That very nicely sums it up! > So this makes sense, though nothing about the naming convention of > these methods makes this particularly clear. However, this brings up > the question: If something acts exactly like an integer method-wise, > whats the benefit of explicitly calling to_int? This seems like a non > duck-typey thing to do. In the example with the roman numerals, you might not want to implement all the behavior of Numeric or Fixnum -- it would make your class unnecessarily complex. Rather just have a #to_int method that returned a normal integer, be that a Fixnum or another object responded to the same methods. In many cases, you have to return a Fixnum, or some methods will complain. This approach means that you can give your roman numeral objects directly as arguments to methods. If they call #to_int on the object before dealing with it, it'll behave just as if it's a Fixnum. # doesn't really have to be an integer, # but what the hell... def double(num) num.to_int * 2 end double(roman_num) Cheers, Daniel