Combining arrays in Ruby

The following array contains two arrays, each of which has 5 integer values:

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

I want to combine them so that it generates five different arrays, combining the values ​​of both arrays with an index of 0.1 .. to 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?

+6
source share
4 answers

What about the 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 may also help you in the future, for 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]] 
+9
source
 a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] a.first.zip(a.last) 
+5
source

If you are sure that your helper arrays are the same length, you can use Array # transpose :

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

As a bonus, it works great with more than two arrays:

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

If you are not sure that your helper arrays are the same length:

 [[1,2,3,4,5],[6,7,8,9], [10,11]].reduce(&:zip).map(&:flatten) #=> [[1, 6, 10], [2, 7, 11], [3, 8, nil], [4, 9, nil], [5, nil, nil]] 

Using transpose in this example will raise an IndexError.

+2
source

Using concurrent assignment:

 a, b = [[1, 2, 3, 4, 5],[6, 7, 8, 9, 10]] a.zip b #=> [[1, 6], [2, 7], [3, 8], [4, 9], [5, 10]] 
+1
source

Source: https://habr.com/ru/post/1011879/


All Articles