6

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?

4 Answers 4

9

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]]
Sign up to request clarification or add additional context in comments.

Comments

5
a = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
a.first.zip(a.last)

Comments

2

If you're sure your sub arrays have 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 fine with more than 2 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're not sure your sub arrays have 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 would throw an IndexError.

Comments

1

Using parallel 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]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.