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.
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]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With