Are there any “simple” explanations of what procs and lambdas are in Ruby?
-
20-09-2019 - |
Question
Are there any "simple" explanations of what procs and lambdas are in Ruby?
Solution
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
.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow