From: Ken Bloom Date: 2008-04-18T14:10:19+09:00 Subject: Re: When are lambdas needed? On Thu, 17 Apr 2008 16:58:44 -0500, Joel VanderWerf wrote: > Avdi Grimm wrote: >> On Thu, Apr 17, 2008 at 5:35 PM, Stedwick >> wrote: >>> Can somebody give me an extremely useful, NOT complicated, example of >>> when lambdas are the absolute perfect solution to a problem? >> >> Every time you use a block in ruby you're using a lambda implicitly. > > Implicitly, but not really. I wonder, was the original question more > like "what are blocks for?" or "yes, I know what blocks are for, but why > are there also these Proc objects, which are instantiated with the > lambda construct?" > > If the latter, then one answer is: when you need the program state that > is encapsulated in a block to persist outside of the method in which it > is used. For example, this happens in event-based frameworks: a setup > method in a client class registers lambdas as event handlers; the > framework doesn't need to know the classes or methods of the client > class, hence loose coupling. As a bonus, these handlers can refer to > shared program state (local variables) in the setup method. There are about a zillion ways to get and use a Proc object in Ruby def foo yield 1 end def bar &baz #baz is a Proc object, and you can pass #that proc object to another method that takes a block foo &baz end a=lambda{|x| x*x} #a is a Proc object b=proc{|x| x*x} #b is a Proc object c=Proc.new{|x| x*x} #c is a Proc object c.call 2 =>4 #you can also use #call on a Proc object c[2] =>4 #or you can "index" it like an Array (which is just a synonym for #call) 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. In other languages (specifically LISP) use of LAMBDA is the most common way to create closures. In Ruby, it's one of the rarest. --Ken -- Ken (Chanoch) Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/