Chad Perrin <perrin / apotheon.com> writes: >> >Wait . . . you mean that *all blocks* are automagically lexical >> >closures, as though declared lexical variables within them have >> >gone out >> >of scope? I imagine I'm probably misunderstanding you, but if not, >> >that's a pretty nifty bit of trickery. >> > >> I'm not sure I understand your question. All blocks (by blocks I mean >> do / end and { } ) are (lexically scoped) closures. > > I'll use a Perl example: > > sub foo { > my $bar = 1; > return sub { print ++$bar }; > } > > my $baz = foo(); > > Voila. $baz contains a lexical closure. This is the case because the > return value from foo() was lexically "closed" by virtue of $bar going > out of scope, but its value still being accessible via the coderef > returned from foo() and assigned to $baz. I'm joining the party late, but try this example: class Example def initialize save_for_later do puts "baz" end bar = 1 nil end def save_for_later(&block) @saved = block end def use_saved eval("bar += 1", @saved.binding) end end foo = Example.new foo.use_saved # => 2 foo.use_saved # => 3 From the Wikipedia definition: [A] closure is a function that refers to free variables in its lexical context. Even if the Ruby block itself contains no reference to free variables, the stored lexical context associated with the block does so implicitly. In the case of: array.each do puts "each!" end the block may be get executed immediately w/o referencing free variables, but the ruby implementation has no way of knowing that. Thus, every block carries around a lexical context which references all free variables in that context. Thus, every block is a closure. -- Marshall T. Vandegrift <mvandegrift / iss.net> ISS.Researcher | 404.236.3986w 518.859.4559m