If you want to get a deep understanding of how closures, blocks, procs & lambdas in Ruby work, check out the code at the attached link.
Here the summary:
^
---------------------------- Section 6: Summary ----------------------------
So, what's the final verdict on those 7 closure-like entities?
"return" returns from closure
True closure? or declaring context...? Arity check?
--------------- ----------------------------- -------------------
1. block (called with yield) N declaring no
2. block (&b => f(&b) => yield) N declaring no
3. block (&b => b.call) Y except return declaring warn on too few
4. Proc.new Y except return declaring warn on too few
5. proc <<< alias for lambda in 1.8, Proc.new in 1.9 >>>
6. lambda Y closure yes, except arity 1
7. method Y closure yes
The things within each of these groups are all semantically identical -- that is, they're different
syntaxes for the same thing:
1. block (called with yield)
2. block (&b => f(&b) => yield)
-------
3. block (&b => b.call)
4. Proc.new
5. proc in 1.9
-------
5. proc in 1.8
6. lambda
-------
7. method (may be identical to lambda with changes to arity checking in 1.9)
Or at least, this is how I *think* it is, based on experiment. There's no authoritative answer other
than testing the CRuby implementation, because there's no real spec -- so there may be other differences
I haven't discovered.
The final verdict: Ruby has four types of closures and near-closures, expressible in seven syntactic
variants. Not pretty. But you sure sure do cool stuff with them! That's up next....
Posted by Dominik Schöler to makandra dev (2011-03-08 15:19)