Ruby实现以下的方法是什么?
a = [1,2]
b = [3,4]
我想要一个数组:
=> [f(1,3) ,f(1,4) , f(2,3) ,f(2,4)]
Ruby实现以下的方法是什么?
a = [1,2]
b = [3,4]
我想要一个数组:
=> [f(1,3) ,f(1,4) , f(2,3) ,f(2,4)]
您可以使用product
先获取数组的笛卡尔积,然后收集函数结果。
a.product(b) => [[1, 3], [1, 4], [2, 3], [2, 4]]
所以你可以使用map
orcollect
来得到结果。它们是相同方法的不同名称。
a.product(b).collect { |x, y| f(x, y) }
a.map {|x| b.map {|y| f(x,y) } }.flatten
注意:在 1.8.7+ 上,您可以添加1
作为 flatten 的参数,因此在f
返回数组时仍然会得到正确的结果。
这是任意数量数组的抽象:
def combine_arrays(*arrays)
if arrays.empty?
yield
else
first, *rest = arrays
first.map do |x|
combine_arrays(*rest) {|*args| yield x, *args }
end.flatten
#.flatten(1)
end
end
combine_arrays([1,2,3],[3,4,5],[6,7,8]) do |x,y,z| x+y+z end
# => [10, 11, 12, 11, 12, 13, 12, 13, 14, 11, 12, 13, 12, 13, 14, 13, 14, 15, 12, 13, 14, 13, 14, 15, 14, 15, 16]
FacetsArray#product
可以为您提供数组的叉积。** operator
对于两个数组的情况,它也有别名。使用它,它看起来像这样:
require 'facets/array'
a = [1,2]
b = [3,4]
(a.product b).collect {|x, y| f(x, y)}
如果你使用的是 Ruby 1.9,product
是一个内置的 Array 函数。