91

Ruby实现以下的方法是什么?

a = [1,2]
b = [3,4]

我想要一个数组:

=> [f(1,3) ,f(1,4) , f(2,3) ,f(2,4)]
4

3 回答 3

162

您可以使用product先获取数组的笛卡尔积,然后收集函数结果。

a.product(b) => [[1, 3], [1, 4], [2, 3], [2, 4]]

所以你可以使用maporcollect来得到结果。它们是相同方法的不同名称。

a.product(b).collect { |x, y| f(x, y) }
于 2009-10-09T13:30:26.703 回答
11
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]
于 2009-10-09T13:05:47.660 回答
5

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 函数。

于 2009-10-09T13:37:04.270 回答