Ruby中两个数组的组合

pie*_*fou 75 ruby combinations

Ruby的实现方式是什么?

a = [1,2]
b = [3,4]
Run Code Online (Sandbox Code Playgroud)

我想要一个数组:

=> [f(1,3) ,f(1,4) , f(2,3) ,f(2,4)]
Run Code Online (Sandbox Code Playgroud)

Aar*_*nni 137

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

a.product(b) => [[1, 3], [1, 4], [2, 3], [2, 4]]
Run Code Online (Sandbox Code Playgroud)

所以你可以使用mapcollect获得结果.它们是同一方法的不同名称.

a.product(b).collect { |x, y| f(x, y) }
Run Code Online (Sandbox Code Playgroud)

  • 产品是1.8.7 - 我用它来完成Pierr所要求的 (7认同)

sep*_*p2k 11

a.map {|x| b.map {|y| f(x,y) } }.flatten
Run Code Online (Sandbox Code Playgroud)

注意:在1.8.7+上你可以添加1一个参数来展平,这样你在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]
Run Code Online (Sandbox Code Playgroud)


Pes*_*sto 5

Facets具有Array#product可为您提供数组叉积的功能。** operator对于两阵列情况,它也被别名为。使用它,它看起来像这样:

require 'facets/array'
a = [1,2]
b = [3,4]

(a.product b).collect {|x, y| f(x, y)}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Ruby 1.9,product则是内置的Array函数。