Are there any "simple" explanations of what procs and lamdbas are in Ruby?
views:
74answers:
1
+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
2009-11-16 08:58:17
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
2009-11-16 10:58:12
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
2009-11-16 16:20:12
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
2009-11-16 17:23:53
That in itself is an example. Without, it'd be `aa=[]; for i in 0...(a.length); aa<<a[i]**2; end; aa`
jtbandes
2009-11-17 02:58:17
Ok, thanks, that was a good example. So it makes the code clearer. Thanks
Zubair
2009-11-17 14:01:34