jeevan
5/9/2007 6:13:00 AM
Array.replace works (at least for my reasonably accurate test code).
i always wondered why Array, Hash, etc. had replace (which seemed superfluous
given that i can just do an assign). now i know at least one good reason why -
they effectively give one a channel to write the instance data of fundamental
classes.
and technically (speaking C here since that's what's currently under the hood),
self isn't the physical array, it's a pointer to an object struct containing an
RBasic struct, a pointer to an instance variable array (one of whose pointers
points to an RArray struct which contains the address of the physical array
storage and the length), and a pointer to the class struct, etc.
thanx again for the pointer :) to replace.
jake
"Brian Candler" <B.Candler@pobox.com> wrote in message
news:20070508075042.GA778@uk.tiscali.com...
> 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.
>