Will Leinweber

bitfission.com


Closures in Ruby

I remember reading that Proc.new and lambda weren't exactly the same, but I never ran into any problems so I never bothered to look up exactly what the differences were. I just always used lambda, which as it turns out, is probably for the best. Paul Cantrell wrote a article/script hybrid that does a great job showing and telling all of the differences with the 7 (who knew?) different ways you can have a closure. It's worth a read, check it out. Here's the summary table that's about halfway through.

                                                    "return" returns
                                                    from closure or
                                   True closure?    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