Are there any "simple" explanations of what procs and lambdas are in Ruby?
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.
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