Rails Proc把block变成对象后,为什么a class 可以调用呢?
After Rails Proc turns a block into an object, why can a class call it?
我得到了一个示例代码,它使用 Proc.new
将一个块变成一个对象,以便它可以独立执行。末尾有两个puts
打印结果,本例将数组带入block执行。在这一点上,我有一点不明白。
在下面的代码中,为什么.iterate!(square)
有效?它们是 class 中定义的方法和单独的块对象的名称。为什么可以写在一起呢?
二、def iterate!(code)
的工作过程是怎样的?为什么要将值带入 (code)
? self
和 code.call
是什么?
square = Proc.new do |n|
n ** 2
end
class Array
def iterate!(code)
self.map {|n| code.call(n)}
end
end
puts [1, 2, 3].iterate!(square)
puts [4, 5, 6].iterate!(square)
我是初学者,请尽量详细说明,谢谢
square = Proc.new do |n|
n ** 2
end
这是一个简单的过程,需要一个整数参数和 return 个参数的平方。
例如:
square.call(5) => 25
square.(5) => 25
现在,您已打开数组 class 并添加了带有参数的 iterate!
方法。并且该方法仅适用于 self (这里的 self 指的是您调用 iterate 方法的同一个数组。这里 self = [1,2,3] 在你的第一种情况下,[4,5,6] 在你的第二种情况下。
迭代中!方法定义,你是 mapping/looping 数组元素,你正在调用 square
过程,每个元素作为参数。
所以更像
square.call(1) => 1
square.call(2) => 4
square.call(3) => 9
我得到了一个示例代码,它使用 Proc.new
将一个块变成一个对象,以便它可以独立执行。末尾有两个puts
打印结果,本例将数组带入block执行。在这一点上,我有一点不明白。
在下面的代码中,为什么.iterate!(square)
有效?它们是 class 中定义的方法和单独的块对象的名称。为什么可以写在一起呢?
二、def iterate!(code)
的工作过程是怎样的?为什么要将值带入 (code)
? self
和 code.call
是什么?
square = Proc.new do |n|
n ** 2
end
class Array
def iterate!(code)
self.map {|n| code.call(n)}
end
end
puts [1, 2, 3].iterate!(square)
puts [4, 5, 6].iterate!(square)
我是初学者,请尽量详细说明,谢谢
square = Proc.new do |n|
n ** 2
end
这是一个简单的过程,需要一个整数参数和 return 个参数的平方。
例如:
square.call(5) => 25
square.(5) => 25
现在,您已打开数组 class 并添加了带有参数的 iterate!
方法。并且该方法仅适用于 self (这里的 self 指的是您调用 iterate 方法的同一个数组。这里 self = [1,2,3] 在你的第一种情况下,[4,5,6] 在你的第二种情况下。
迭代中!方法定义,你是 mapping/looping 数组元素,你正在调用 square
过程,每个元素作为参数。
所以更像
square.call(1) => 1
square.call(2) => 4
square.call(3) => 9