Combine array of array into all possible combinations, forward only, in Ruby

Travis picture Travis · Mar 8, 2011 · Viewed 7.7k times · Source

I have an array of arrays, like so:

[['1','2'],['a','b'],['x','y']]

I need to combine those arrays into a string containing all possible combinations of all three sets, forward only. I have seen lots of examples of all possible combinations of the sets in any order, that is not what I want. For example, I do not want any of the elements in the first set to come after the second set, or any in the third set to come before the first, or second, and so on. So, for the above example, the output would be:

['1ax', '1ay', '1bx', '1by', '2ax', '2ay', '2bx', '2by']

The number of arrays, and length of each set is dynamic.

Does anybody know how to solve this in Ruby?

Answer

Andrew Grimm picture Andrew Grimm · Mar 8, 2011

Know your Array#product:

a = [['1','2'],['a','b'],['x','y']]
a.first.product(*a[1..-1]).map(&:join)