tags:

views:

74

answers:

1

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

+5  A: 

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.

jtbandes
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.
Zubair
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
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.
Zubair
That in itself is an example. Without, it'd be `aa=[]; for i in 0...(a.length); aa<<a[i]**2; end; aa`
jtbandes
Ok, thanks, that was a good example. So it makes the code clearer. Thanks
Zubair