From: Joel VanderWerf Date: 2003-06-24T14:28:33+09:00 Subject: Re: Block Scope Statement in the Pickaxe Robert Klemme wrote: > Hi, > > I stumbled across this quote in chapter 15, "Ruby Tk", which confused me a > bit: > > "One small caution when using the code block form: the scope of variables is > not what you think it is. The block is actually evaluated in the context of > the widget's object, not the caller's. This means that the caller's instance > variables will not be available in the block, but local variables from the > enclosing scope and globals (not that you ever use those) will be." > > How can this be? I mean, AFAIK the block's binding refers to client code > and cannot be changed afterwards. Or did I miss something? Is this some > kind of implementation trick that can be done with a Ruby extension? I think this is just the distinction between #instance_eval and calling a block directly. With instance_eval, the binding of self in the block is changed to the receiver of instance_eval. Hope this example says it better: class A attr_reader :x def initialize @x = 1 end def twiddle(&block) block.call end def frob(&block) instance_eval(&block) end end a = A.new some_local_var = 2 @x = 10 a.twiddle do some_local_var += 1 @x += 1 end p some_local_var, @x, a.x # => 3, 11, 1 a.frob do some_local_var += 1 @x += 1 end p some_local_var, @x, a.x # => 4, 11, 2