1

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.

1 Answer 1

2
>> mega_array[0].product(*mega_array[1..-1]).map(&:join)
=> ["ace", "acf", "ade", "adf", "bce", "bcf", "bde", "bdf"]
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. Nailed it! Thank you very much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.