I've tried reading about procs and lambda's but I have to keep re-reading the definition.
Can someone explain it to me in a way that is clear and memorable?
The way I think about them is that a lambda behaves more like a function and a Proc or block behaves more like a control structure.
I think the best way to understand why the two exist and what the difference is is to understand how each is used. Take this code for example:
def find (elem)
@array.each { |item| return item if item == elem }
return false
end
It's obvious to anyone familiar with Ruby what happens here, but ask yourself what you are returning from when that return
is called. What you expect, and what happens, is that the method itself returns. Even though we are inside a block of code, it is the method returning, not just the block. That is how a Proc behaves, and it's what lets us use an .each
loop and return from it just like we would in an equivalent for
loop.
On the other hand, lambdas are like functions. If you return from inside a lambda, it exits only from the lambda.
def find (elem)
l = lambda { |item| return item if item == elem }
@array.each(&l)
return false
end
Here, the method would always return false due to the final line not being bypassed by a return
call in the lambda. Lambdas are functions and return from themselves, whereas Procs return from the enclosing method.
So, Procs and blocks and return from the method using them (like a loop would), while lambdas (like methods) return from themselves.
Edited: After reading other good answers here, I offer the following distillation that might save you some re-reading:
(l)ambda -
(L)ocal return
(L)ooks at the arguments
(p)roc -
(P)ops you out of the method when it returns.
(P)ermits different arguments
Einstein said to "... make things as simple as possible, but no simpler." If he had stack overflow, he would have pointed you here:
What are the differences between a proc and lambda?
or here:
What's the difference between a proc and a lambda in Ruby?
hth -
Perry
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With