From: David Alan Black Date: 2002-05-02T23:58:27+09:00 Subject: Re: A scoping issue Hello -- On Thu, 2 May 2002, Harry Ohlsen wrote: > I'm trying to write a class that constructs a Tk > dialog and am hitting an issue to do with the scope > of instance variables. > > As part of the processing, what I want is something > similar to the following code (I've made it non-Tk, > to show up the essence of the problem) ... > > class A > def initialize(&block) > @code = block > end > end > > class B > def initialize > @x = 123 > > a = A.new(proc { puts @x }) > a.execute > end > end > > The problem is that, of course, the reference to @x > assumes it's an instance variable of class A, rather > than the one from class B, in the outer scope. > > Is there some way I can get the block passed to the > A.new to end up with the @x from the instance of B > that I'm constructing? It looks like you're sending a proc as a regular argument, rather than as a block, but A#initialize is expecting a block. I've tweaked it so that it's all block-wise. Also I've added some tracer variables, just to make stuff visible. Here's the result: class A attr_reader :code def initialize(&block) @code = block end end class B attr_reader :a def initialize @x = 123 @a = A.new { puts @x } end end B.new.a.code.call # => 123 David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav