Read more

Closures in Ruby

Dominik Schöler
March 08, 2011Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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 16:19)