1

I have an array which structure [a, [b], c, [d], ...], for example:

array = [0, [1], 2, [1]]

And I need:

[[0, 1], [2, 1]]

How do I do it? :P

Update:

I was wondering how wil handle this array

array = [0, [], 1, [], 2, []]

into

[[0, 1], [2, 1]]

That is remove the empty ones and merge as shown above accordingly.

Thanks :)

2 Answers 2

2

I'd write:

array.each_slice(2).map { |x, ys| [x, ys.first] }
#=> [[0, 1], [2, 1]]

Note that you can also write map { |x, (y)| [x, y] } though it's certainly a cryptic unpacking.

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

2 Comments

Hello there, can you help me with the updated question/section above? .Thank you :)
actually its ok. i got it. :)
2
array.flatten.each_slice(2).to_a

2 Comments

Hello there, can you help me with the updated question/section above? .Thank you :)
actually its ok. i got it.

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.