Possible Duplicate:
When to use lambda, when to use Proc.new?
(I know it had been asked several times but I couldn’t find satisfactory answer)Can somebody please explain Blocks, Procs and Lambdas and why one should be used over other, what are the situation when one should use proc, similar and/or lambda. Also there effect on computer memory. Practical examples please.
Try Robert Sosinski’s Tutorial or Learning to Program by Chris Pine.
For more foundation I suggest you read Why’s (poignant) Guide to Ruby. This guide is responsible for creating many of nowadays Ruby’s Pro! Make sure to take a look!
Explanation by Joey deVilla
Another important but subtle difference is in the way procs created with
lambdaand procs created withProc.newhandle thereturnstatement:lambda-created proc, thereturnstatement returns only from the proc itselfProc.new-created proc, thereturnstatement is a little more surprising: it returns control not just from the proc, but also from the method enclosing the proc!Here’s
lambda-created proc’sreturnin action. It behaves in a way that you probably expect:Now here’s a
Proc.new-created proc’sreturndoing the same thing. You’re about to see one of those cases where Ruby breaks the much-vaunted Principle of Least Surprise:Thanks to this surprising behaviour (as well as less typing), I tend to favour using
lambdaoverProc.newwhen making procs.