From: Rajinder Yadav Date: 2010-11-01T07:54:22+09:00 Subject: Re: the dark side of inherited methods On 10-10-31 06:42 PM, Phillip Gawlowski wrote: > 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. ;) > I see how Vector is-a Array, I don't see how Array is-a Vector? I would consider collect and collect! to be inconsistent under this definition. -- Kind Regards, Rajinder Yadav | DevMentor.org | Do Good! ~ Share Freely GNU/Linux: 2.6.35-22-generic Kubuntu x86_64 10.10 | KDE 4.5.1 Ruby 1.9.2p0 | Rails 3.0.1