From: Phillip Gawlowski Date: 2010-11-01T07:42:14+09:00 Subject: Re: the dark side of inherited methods On Sun, Oct 31, 2010 at 11:30 PM, timr wrote: > I noticed that I inherited the Array#collect and Array#collect! > methods. Yeah for inheritance! But then look at the returned classes. > Array#collect returns and array. Array.collect! returns a Vector. If > you look at the underlying C code that defines these methods the > response makes sense. Collect! alters the object itself using the > results from the block, while collect builds a new Array from the > results of the block. But geesh, that means to have consistent > behavior, I have to add the following (and worse, look through every > other Array method to determine if the return value should be a vector > rather than an array): Define "consistent behavior". That #collect returns an Array is consistent with other, similar language constructs. The question is if you want an Array back, or want a Vector back from the operation you perform. Similarly, since you inherited the Array methods, Vector#join will behave exactly like Array#join. That's pretty much the point of inheritance: Re-using a class's methods to make your own life easier by reducing the work you need to do, since most methods you expect to use are identical to what you need, and only need adaptation to your own needs (via encapsulation, or overriding, for example). Maybe you have better success (i.e. less work), if you a) encapsulate similar calls into calls of your own and massage the operation that way, or b) you move one up in the inheritance change, and use Enumerable to inherit from. Most work will be c) create your class from scratch, and mix in Array or Enumerable. TL;DR: Any class derived from another class will inherit its method. That's true for Ruby, as it is for Java or C#. It's pretty much the point of inheritance. ;) -- Phillip Gawlowski Though the folk I have met, (Ah, how soon!) they forget When I've moved on to some other place, There may be one or two, When I've played and passed through, Who'll remember my song or my face.