Jeet Sharma
Jeet Sharma

Reputation: 69

How do I convert every two value of array into its own array in ruby?

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 :)

Upvotes: 1

Views: 66

Answers (2)

tokland
tokland

Reputation: 67890

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.

Upvotes: 2

halfelf
halfelf

Reputation: 10107

array.flatten.each_slice(2).to_a

Upvotes: 2

Related Questions