From: Jim Weirich Date: 2002-03-17T11:03:31+09:00 Subject: Re: Could we subclass this way? >>>>> "Hubert" == Hubert Hung-Hsien Chang writes: Hubert> Here is a question: Hubert> Suppose I have a class called "Monster" with a instance variable Hubert> (@tricks) and two subclasses Hubert> called "Little_vampire" "Little_ghost" but I would like to name Hubert> each of the subclass's @tricks differently. Hubert> I would like to have @vampire_tricks, @ghost_tricks respectively. Hubert> But I wuld still like to use the Monster's methods. And both Hubert> @vampire_tricks and @ghost_tricks will refect the value Hubert> of @tricks from "Monster" Hubert> I haven't successfully done it easily. Any way out? Don't use "@" sytle names, Use accessor functions instead. See the code below for an example. Just remember, if you assign to an accessor, include "self." ... otherwise Ruby will think its a local variable (see add_tricks for an example). ---------------------------------------------------------------------- class Monster attr_reader :tricks def initialize @tricks = [] end def show_tricks puts "My Trickes are: #{tricks.join(' ')}" end end class Vampire < Monster def vampire_tricks @tricks end def vampire_tricks=(value) @tricks = value end def add_tricks(tricks) self.vampire_tricks += tricks end end vamp = Vampire.new vamp.add_tricks %w(bite fly) ---------------------------------------------------------------------- -- -- Jim Weirich jweirich@one.net http://w3.one.net/~jweirich --------------------------------------------------------------------- "Beware of bugs in the above code; I have only proved it correct, not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)