On Mon, 23 Jan 2006, Vladimir Agafonkin wrote: > What is the best way to access class' instance variables from a method of > another instance variable of the same class that is a class itself? :-) > > OK, Let's say I have Duck class with an instance variable @quack_behaviour > of QuackBehaviour class inside. Duck#quack method calls one of the > QuackBehaviour methods, and I want to access some of the intance variables > (say, @name) of the caller Duck object from that method. > > One way is to set an attr_accessor :name (or use instance_variable_get) and > pass "self" as a parameter to the @quack_behaviour method. But it seems for > me that it is not the most appropriate way of doing this. Or is it? harp:~ > cat a.rb class Duck attr_accessor "quack_behaviour" def initialize(quack_behaviour) self.quack_behaviour = quack_behaviour::new(self) end def quack() quack_behaviour.quack end def name() "duck" end end class QuackBehaviour def self::duck_attr a module_eval <<-code def #{ a }() duck.#{ a } end def #{ a }=(val) duck.#{ a }=val end code end attr_accessor "duck" duck_attr "name" def initialize(duck) self.duck = duck end def quack() p name end end duck = Duck::new(QuackBehaviour) duck.quack harp:~ > ruby a.rb "duck" is one way. if you need to dynamically change the quack_behaviour object i'd make a method that pushed/popped/ensured a QuackBehaviour object was in effect - but having the QuackBehaviour object have a reference to their parent, if possible, simplifies things. regards. -a -- strong and healthy, who thinks of sickness until it strikes like lightning? preoccupied with the world, who thinks of death, until it arrives like thunder? -- milarepa