From: Kent Dahl Date: 2002-06-14T22:13:07+09:00 Subject: Re: referring to variables in the scope outside the def k wrote: > > When defining a singleton method, I want to refer to variables in the scope > outside the def. Is it possible to do something like the following? > > class C > def initialize > @child = Object.new > s = self > def @child.parent > s # Wrong. But how do I refer to the instance of C? > end > end > attr_reader :child > end > > c = C.new > c == c.child.parent # Should be true. > > Any hints? I think I'm missing a vital piece of magic here. Or maybe I'm > expecting too much Lisp-ness. Probably the latter. A method doesn't have access to the surrounding scope as such. I suggest feeding it into an attribute in the child object. Quick stab: class C def initialize @child = Object.new s = self # feed the variable into it @child.instance_eval { @parent_C = s } # define the method for retrieving it def @child.parent @parent_C end end attr_reader :child end c = C.new puts c == c.child.parent # Is now true HTH -- (\[ Kent Dahl ]/)_ _~_ __[ http://www.stud.ntnu.no/~kentda/ ]___/~ ))\_student_/(( \__d L b__/ NTNU - graduate engineering - 4. year ) ( \__\_�|�_/__/ ) _)Industrial economics and technological management( \____/_�_\____/ (____engineering.discipline_=_Computer::Technology___)