Nathan Long
Nathan Long

Reputation: 125902

What's the simplest way in Ruby to group an array of arrays by element order?

What's the simplest way in Ruby to group an array of arrays by element order? In other words, to get all the 0th elements, then all the 1th elements, etc.

So if you started with this:

[[1,2], [:a, :b], [:alpha, :beta]]

you'd get this:

[[1, :a, :b], [2, :b, :beta]]

I can do it with zip:

arr = [[1,2], [:a, :b], [:alpha, :beta]]
arr[0].zip(arr[1], arr[2])

... but I'd like a more general way that would work for any number of inner arrays of any length.

Upvotes: 3

Views: 381

Answers (1)

Paul Prestidge
Paul Prestidge

Reputation: 1127

I think Array#transpose is what you're after:

a = [[1,2], [:a, :b], [:alpha, :beta]]
p a.transpose #=> [[1, :a, :alpha], [2, :b, :beta]]

Upvotes: 3

Related Questions