Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining arrays in Ruby

Tags:

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?

like image 362
Arif Avatar asked Oct 31 '16 10:10

Arif


Video Answer


2 Answers

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]]
like image 105
Alex Holubenko Avatar answered Sep 18 '22 22:09

Alex Holubenko


a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
a.first.zip(a.last)
like image 38
Ursus Avatar answered Sep 20 '22 22:09

Ursus