使用product方法时保持对象数组

时间:2014-09-23 22:43:15

标签: ruby arrays

我有几个对象需要使用产品才能获得所有可能的组合。

当我执行以下操作时,它可以正常工作 -

combinations = a1.product(a2,a3)
#combinations.class = Array
#combinations[0].class = Object

但是如果我稍后尝试使用相同的方法添加数组,它会将其转换为对象数组的数组 -

combinations = combinations.product(a4)
#combinations.class = Array
#combinations[0].class = Array
#combinations[0][0].class = object

我需要更改维护对象和数组?

1 个答案:

答案 0 :(得分:1)

假设你有

a = [:a1, :a2]
b = [:b1, :b1]
c = [:c1, :c2]

e = a.product(b,c)
  #=> [[:a1, :b1, :c1], [:a1, :b1, :c2], [:a1, :b1, :c1], [:a1, :b1, :c2],
  #    [:a2, :b1, :c1], [:a2, :b1, :c2], [:a2, :b1, :c1], [:a2, :b1, :c2]]

当您使用e的产品时:

d = [:d1, :d2]

你得到:

f = e.product(d)
  #=> [[[:a1, :b1, :c1], :d1], [[:a1, :b1, :c1], :d2], [[:a1, :b1, :c2], :d1],
  #    [[:a1, :b1, :c2], :d2], [[:a1, :b1, :c1], :d1], [[:a1, :b1, :c1], :d2],
  #    [[:a1, :b1, :c2], :d1], [[:a1, :b1, :c2], :d2], [[:a2, :b1, :c1], :d1],
  #    [[:a2, :b1, :c1], :d2], [[:a2, :b1, :c2], :d1], [[:a2, :b1, :c2], :d2],
  #    [[:a2, :b1, :c1], :d1], [[:a2, :b1, :c1], :d2], [[:a2, :b1, :c2], :d1],
  #    [[:a2, :b1, :c2], :d2]]

但你想要的是:

a.product(b,c,d)
  #=> [[:a1, :b1, :c1, :d1], [:a1, :b1, :c1, :d2], [:a1, :b1, :c2, :d1],
  #    [:a1, :b1, :c2, :d2], [:a1, :b1, :c1, :d1], [:a1, :b1, :c1, :d2],
  #    [:a1, :b1, :c2, :d1], [:a1, :b1, :c2, :d2], [:a2, :b1, :c1, :d1], 
  #    [:a2, :b1, :c1, :d2], [:a2, :b1, :c2, :d1], [:a2, :b1, :c2, :d2],
  #    [:a2, :b1, :c1, :d1], [:a2, :b1, :c1, :d2], [:a2, :b1, :c2, :d1],
  #    [:a2, :b1, :c2, :d2]]

您可以通过将g的{​​{1}}的每个元素映射到f来获得所需的结果,如@DavidUnric所建议的那样::

g.flatten

或者你可以这样做:

e.product(d).map(&:flatten)