好的,通过这个 link 查看 Procs、lambdas 和 block .
关于这段代码的问题:
class Array
def iterate!
self.each_with_index do |n, i|
self[i] = yield(n)
end
end
end
array = [1, 2, 3, 4]
array.iterate! do |n|
n ** 2
end
puts array.inspect
从概念上讲,我几乎理解所有内容,除了一行是这样的:
self[i] = yield(n)
我在这一行 self.each_with_index do |n, i|
中得到这个 self 意味着它是一个类方法,对吧?
但是为什么我们需要将yield(n)
中的参数赋值给self[i]
呢?
如果可以,请用 super 基本的方式解释。
(换句话说,请保持友善 - 这里的大部分人通常都是这样的 - 只是有点特别紧张,因为我不明白这让我觉得自己很愚蠢)
最佳答案
方法是iterate!
,是一个实例方法。 self.each_with_index
中的self
是方法Enumerable#each_with_instance 的接收者.由于 self
是 Array
的当前实例(在您的示例中为 [1,2,3,4]
),self.
不需要;即,您可以(并且我认为应该)只编写 each_with_index do |n, i|...
。换句话说,self
是未指定显式接收者时的隐含接收者。
关于线路:
self[i] = yield(n)
对于您的示例array = [1,2,3,4]
,您的枚举器是:
enum = [1,2,3,4].each_with_index
#=> #<Enumerator: [1, 2, 3, 4]:each_with_index>
有元素
enum.to_a
#=> [[1, 0], [2, 1], [3, 2], [4, 3]]
因此,Array#each
传入 block 的第一个元素是 [1,0]
,它被分配给 block 变量:
n = 1
i = 0
导致
self[0] = yield(1) => 1**2 => 1
等等。
关于ruby - Procs 来自 "Understanding Ruby Blocks, Procs, and Lambdas"文章,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26600610/