1

I have multiple arrays, lets say 4 for example:

a = ["a", "b", "c" ]
b = [1, 2, 3, 4]
c = ["xx", "yy"]
d = ["abc"]

I'd like to "progressively" do product of arrays in an iterative fashion, something like this

a.product(b)
a.product(b, c)
a.product(b, c, d)

I want to be able to do in a scalable fashion where the array count varies and get array product upto arr0.product(arr1, arr2, arr3.......arrn).Could someone please help figure out how to do this in Ruby. Thanks in advance!

2 Answers 2

3
a = ["a", "b", "c" ]
b = [1, 2, 3, 4]
c = ["xx", "yy"]
d = ["abc"]

ars = [b,c,d]
p ars.each_index.flat_map{|i| a.product(*ars[0..i])}
Sign up to request clarification or add additional context in comments.

Comments

2

You could abstract it like this:

def prog_product(arrs)
  x, *xs = arrs
  (1..xs.count).map(&xs.method(:take)).map do |args|
    x.product(*args)
  end
end

This will return an array of the progressive products, such as:

[a1.product(a2), ..., a1.product(a2, ..., an)]

In your case, prog_products(a, b, c, d) would return [a.product(b), a.product(b, c), a.product(b, c, d)]. If for some reason you wanted to merge all the products into one big array, you may call .flatten(1) on the result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.