有没有一种很好的方法来创建一个Ruby数组链,在飞行中结合map和注入?
我的意思是这样的。让 a
是一个整数数组,那么要想得到相邻2个元素的所有和,我们可以这样做。
a.each_cons(2).map(&:sum)
我们也可以得到一个数组中所有元素的乘积。a
由。
a.inject(1,&:*)
但我们不能这样做。
a.each_cons(2).map(&:inject(1,&:*))
但我们可以定义一个可链式数组
class Array
def prod
return self.inject(1,&:*)
end
end
那么 a.each_cons(2).map(&:prod)
运作良好。
如果你使用这个奇怪的Symbol补丁,如这里所示。
https: /stackoverflow.coma237116062981429
class Symbol
def call(*args, &block)
->(caller, *rest) { caller.send(self, *rest, *args, &block) }
end
end
这允许你通过以下方式向proc速记传递参数 咖喱:
[[1,2],[3,4]].map(&:inject.(1, &:*))
# => [2, 12]
我相信这个问题在Ruby core里已经被请求过很多次了,可惜我现在没有Ruby论坛的链接,但我保证它就在那里。
我怀疑这是不是你要找的东西,但是别忘了你仍然可以调用 map
用一个普通的块。
a.each_cons(2).map { |n1, n2| n1 * n2 }
既然你在问题中没有提到,我想你可能忽略了最简单的选择。