Hi --

"Robert Klemme" <bob.news / gmx.net> writes:

> "Shashank Date" <sdate / everestkc.net> schrieb im Newsbeitrag
> news:c5id4r$22o3g$1 / ID-194283.news.uni-berlin.de...
> > In one of Matz's slides at RubyConf ,
> >
> > (http://www.rubyist.net/~matz/slides/rc2003/mgp00012.html)
> >
> > he mentions his New Local Variable Scope rule as follows:
> >
> > #---------------------------------------------------------------
> > def foo
> >     a = nil
> >     ary.each do |b|
> >         # b is block local
> >         c = b
> >         a = b
> >         # a and c are local to the method
> >     end
> >     # a and c available here
> > end
> > #---------------------------------------------------------------
> >
> > I was wondering what would happen if it was written as follows:
> >
> > #---------------------------------------------------------------
> > def foo(&block)
> >     a=nil;
> >     ary.each(&block)
> > end;
> >
> > foo(lambda {|b| a=b; c=b})
> > #---------------------------------------------------------------
> 
> First of all both examples are erroneous IMHO because ary is not defined
> in foo().

OK, OK...  def ary; [1,2,3]; end  :-)

> > In other words, in general, what is the advantage of having variables in
> > closures leak out?
> 
> Your second example will not modify the a defined in foo() because the
> binding takes place at the point of invocation, i.e. another scope.  If
> you do

I think you mean the point of creation (of the closure), rather than
invocation?

> def foo(&block)
>     a=nil;
>     ary.each(&block)
>     puts "a=#{a.inspect}"
> end;
> 
> foo(lambda {|b| a=b; c=b})
> puts "a*#{a.inspect}"
> 
> You'll see
> a=nil
> a*<last enum element>

OK, but there's still 'c'.  The new thing is the idea of a local
variable created in a block and persisting after the block exits.  If
the scope that matters is where the block was created, then what
happens in this case:

  def call_foo
    foo(lambda{|b| c=b})
    puts c                # does c persist if the lambda was called?
  end


David

-- 
David A. Black
dblack / wobblini.net