Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 977
Nathan Long Avatar asked Feb 02 '26 15:02

Nathan Long


1 Answers

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]]
like image 81
Paul Prestidge Avatar answered Feb 04 '26 07:02

Paul Prestidge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!