From: "David A. Black" Date: 2008-04-18T21:48:45+09:00 Subject: Re: When are lambdas needed? Hi -- On Fri, 18 Apr 2008, Rick DeNatale wrote: > On Fri, Apr 18, 2008 at 6:43 AM, David A. Black wrote: >> Hi -- >> >> >> On Fri, 18 Apr 2008, Ken Bloom wrote: >> >> >>> The difference between lambda and the other ways of getting a Proc object >>> is that lambda treats return, next, and break a little bit differently. >>> >> >> It's actually a difference between lambda and proc (which are >> synonyms), on the one hand, and Proc.new on the other: >> >> irb(main):009:0> lambda { return }.call >> => nil >> irb(main):010:0> proc { return }.call >> => nil >> irb(main):011:0> Proc.new { return }.call >> LocalJumpError: unexpected return > > Another difference between lambdas and procs, is that procs are less > strict about arity when they are called. Yes, assuming that by "proc" you mean Proc.new and not proc.... > 1: p = Proc .new {|x,y| [x,y]} > 2: l = lambda {|x,y| [x, y]} > 3: > 4: p.call(1) # => [1, nil] > 5: l.call # => > # ~> -:5: wrong number of arguments (0 for 2) (ArgumentError) > # ~> from -:5:in `call' > # ~> from -:5 > > procs are invoked using the same semantics as a yield, which acts like > parallel assignment with nils being provided for missing arguments. > > lambdas are invoked using the same semantics as a message send. > >> Since it's a bit confusing to have proc and Proc.new be different, >> this has been changed in 1.9: proc and Proc.new are the same in 1.9, >> and lambda is different. >> >> (I still have no idea how to memorize which is which.) > > Thinking about this a bit, I think that the basic rule is that procs > act like blocks, in that: > > arguments are passed to them using yield semantics > and > return effects a return from the activation of the code containing > the source of the block > break breaks out of the block into the activation of the code > containing the source of the block > > Lambdas act like methods in that: > > arguments are passed to them using method call semantics > and > return effects a return from the body of the lambda > break breaks out of the body of the lambda, back to the caller, > effectively becoming a return > > So a double mnemonic might be: > > proc rhymes with block > lambda and method both have and m while proc does not. The problem is that proc also rhymes with Proc :-) David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates!