Stevan O. Stevan O. - 6 months ago 21
Ruby Question

How to create new 2D array starting from another two arrays Ruby

I have two arrays

A = [1, 2, 3, 4, 5]

B = [2, 3]


I want a C array like this

C = [[1,2], [1,3], [2,2], [2,3], [3,2], [3,3] ...]


any ideas?

Answer

You can use product to get the cartesian product of the arrays first, then collect the function results.

>> A = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
>> B = [2, 3]
=> [2, 3]
>> A.product(B)
=> [[1, 2], [1, 3], [2, 2], [2, 3], [3, 2], [3, 3], [4, 2], [4, 3], [5, 2], [5, 3]]