Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need a memorable explanation of a proc and lambda

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?

like image 732
Blankman Avatar asked Apr 28 '11 13:04

Blankman


2 Answers

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.

like image 183
evnkm Avatar answered Sep 19 '22 20:09

evnkm


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

like image 30
Perry Horwich Avatar answered Sep 20 '22 20:09

Perry Horwich