From: Brian Candler Date: 2007-05-08T16:50:51+09:00 Subject: Re: subclassing fundamental classes On Tue, May 08, 2007 at 03:20:12PM +0900, xyz wrote: > class C3 < Array > def initialize(inArray) > ??? = inArray > end > def append(i) > ??? << i << i > return(self) > end > def join(i) > out = "" > sep = "#" * i > ???.each { |e| out << sep + e.to_s + sep } > return(out) > end > end > > What do I use in place of the ???'s above? That is, what name do I use in the > subclass (C3) for the instance state of a fundamental superclass (Array)? self. An Array doesn't store its array in an instance variable; the object *is* the array. You can add instance variables in your subclass though. You may find Array#replace useful, if you want to replace your array contents with another array. (So 'self' still points to the same object of course, but the array contents are different). This is almost the same as having the array in @iv and then changing @iv to point to another array. The difference is that if you had @iv, you could point it to some other object which *isn't* an array. > In my specific case, I am using instances of Array to hold data in a particular > format (the array elements are Hash's whose keys are String's of a particular > format and whose values are Hash's of a particular format). I want to subclass > Array, add a couple of methods, override a couple of methods, and also use the > non-overridden methods of Array. Consider delegation instead of subclassing. In the long run it gives you more flexibility. Subclassing is the evil you learn from Object Oriented Programming courses. It's taught so thoroughly that you come to believe that subclassing *is* OOP. In fact, once you ditch subclassing, and worrying whether a Square is a Rectangle or vice versa, life becomes much more straightforward :-) Regards, Brian.