Arif Arif - 1 month ago 9
Ruby Question

Combining arrays in Ruby

The following array contains two arrays each having 5 integer values:

[[1,2,3,4,5],[6,7,8,9,10]]


I want to combine these in such a way that it generates five different arrays by combining values of both arrays at index 0,1.. upto 4.

The output should be like this:

[[1,6],[2,7],[3,8],[4,9],[5,10]]


Is there any simplest way to do this?

Answer

What about transpose method?

a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
#=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] 

a.transpose
#=> [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]]

this method also can help you in future, as example:

a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]
#=> [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]

a.transpose
#=> [[1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9, 14], [5, 10, 15]]