I have several array of objects that I need to use product on to get all possible combinations.
When I do the following, it works fine-
combinations = a1.product(a2,a3)
#combinations.class = Array
#combinations[0].class = Object
But if I try to add an array later using the same method, it will turn it into an array of arrays of objects-
combinations = combinations.product(a4)
#combinations.class = Array
#combinations[0].class = Array
#combinations[0][0].class = object
What do I need to change to maintain and array of objects?
Suppose you have
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]]
When you take the product of e
with:
d = [:d1, :d2]
you get:
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]]
but what you want is:
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]]
You can obtain the result you want by mapping each element of g
of f
to g.flatten
, as @DavidUnric suggested::
e.product(d).map(&:flatten)
or you could do it like this:
e.product(d).map { |a,f| a + [f] }
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments