5

对 Ruby 中的 procs 和 lambdas 有什么“简单”的解释吗?

4

1 回答 1

5

Lambdas(也存在于其他语言中)就像 ad hoc 函数,只是为了简单的使用而不是为了执行一些复杂的操作而创建的。

当您使用像Array#collect这样的方法时{},您实际上是在创建一个 lambda/proc/block 仅用于该方法的使用。

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

请参阅Wikipedia 上的匿名函数,以及其他一些关于vs.细微差别的SO 问题lambdaProc

于 2009-11-16T08:58:17.127 回答