1

I have this array:

a = [[1,2,3,4,5],[3,5,6,8,12,45],[3,2,1,5,7,9,10,11],[3,5,6,8,2,1,3,4,6]]

I want to merge its inner arrays so that they become:

a = [[1,2,3,4,5,3,5,6,8,12,45],[3,2,1,5,7,9,10,11,3,5,6,8,2,1,3,4,6]]

How can I do this?

1 Answer 1

5

You need to do

 a = [
     [1, 2, 3, 4, 5],
     [3, 5, 6, 8, 12, 45],
     [3, 2, 1, 5, 7, 9, 10, 11],
     [3, 5, 6, 8, 2, 1, 3, 4, 6]
 ]

a.each_slice(2).map(&:flatten)

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

Read the method each_slice(n)

Iterates the given block for each slice of n elements. If no block is given, returns an enumerator.

Sign up to request clarification or add additional context in comments.

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.