Noel Llevares
Noel Llevares

Reputation: 16087

Concatenating multiple arrays in ruby

I'm trying to make a method that accepts a nested array. From that nested array, I need to return all possible combinations that can be made by the sub-arrays. I have been working on it for hours now and I still can't get it to work.

It's like concatenating each element of a sub_array with each element from the other sub_arrays.

example:

mega_array = [["a","b"],["c","d"],["e","f"]]

my_method(mega_array)

=> ["ace","acf","ade","adf","bce","bcf","bde","bdf"]

This would have been accomplished by the following code:

mega_array[0].each do |first|
    mega_array[1].each do |second|
        mega_array[2].each do |third|
            puts first + second + third
        end
    end
end

Unfortunately, the number of subarrays can vary. This is where I'm stuck. Tried to do some recursive techniques but I still don't get it right.

Help will be greatly appreciated. I need to make this work with the vanilla Ruby that comes with Leopard and up. It's 1.8.7, right?

Thanks.

Upvotes: 1

Views: 108

Answers (1)

tokland
tokland

Reputation: 67900

>> mega_array[0].product(*mega_array[1..-1]).map(&:join)
=> ["ace", "acf", "ade", "adf", "bce", "bcf", "bde", "bdf"]

Upvotes: 2

Related Questions