5

Are there any "simple" explanations of what procs and lambdas are in Ruby?

Cœur
  • 37,241
  • 25
  • 195
  • 267
yazz.com
  • 57,320
  • 66
  • 234
  • 385

1 Answers1

5

Lambdas (which exist in other languages as well) are like ad hoc functions, created only for a simple use rather than to perform some complex actions.

When you use a method like Array#collect that takes a block in {}, you're essentially creating a lambda/proc/block for only the use of that method.

a = [1, 2, 3, 4]
# Using a proc that returns its argument squared
# Array#collect runs the block for each item in the array.
a.collect {|n| n**2 } # => [1, 4, 9, 16]
sq = lambda {|n| n**2 } # Storing the lambda to use it later...
sq.call 4 # => 16

See Anonymous functions on Wikipedia, and some other SO questions for the nuances of lambda vs. Proc.

Community
  • 1
  • 1
jtbandes
  • 115,675
  • 35
  • 233
  • 266
  • In the above example it could still be done without the lambda. Isn't the collect the same as a for next loop with the block being the body? I'm just trying to see the advantages of using the block. – yazz.com Nov 16 '09 at 10:58
  • Of course you could do it with a for loop, but this is a more elegant and Ruby-ish way to do it. Other methods might be harder to duplicate with a loop. – jtbandes Nov 16 '09 at 16:20
  • Ok, I guess it would be useful to know what things I can do with Lambdas and Procs that would be too verbose otherwise, maybe with an example. – yazz.com Nov 16 '09 at 17:23
  • That in itself is an example. Without, it'd be `aa=[]; for i in 0...(a.length); aa< – jtbandes Nov 17 '09 at 02:58
  • Ok, thanks, that was a good example. So it makes the code clearer. Thanks – yazz.com Nov 17 '09 at 14:01