From: hubert@... (Hubert Hung-Hsien Chang) Date: 2002-03-17T22:39:02+09:00 Subject: Re: Could we subclass this way? Thank you. Ron and Jim. I don't know much about doing an abstract class in Ruby. Jim's method works ( by naming the 'variable' as method) and it does the tricks. Just curious how 'bad' my understanding on observable. What is wrong with the following code? It is one of the 'failed' version of my trying... ----------------------- require 'observer' class Monster include Observable attr_reader :tricks def initialize @tricks = [] self.add_observer(self) end def spook(value) print "spooking:" notify_observers(value) end end class Ghost < Monster def update(value) print "Ghost scares", value,"\n" end end class Vampire < Monster def vampire_tricks @tricks end def update(value) print "Vampire scares", value,"\n" end end vamp = Vampire.new vamp.spook("charles") ghost = Ghost.new ghost.spook("brown") ----------------------- Jim Weirich wrote in message news:... > >>>>> "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) > ----------------------------------------------------------------------