Are there any "simple" explanations of what procs and lambdas are in Ruby?
开发者_高级运维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
.
精彩评论