kevin change - 1 year ago 49

Ruby Question

Thanks in advance for your time -- I've been looking online and am not sure if I'm using the right words to ask this question.

I have

`original_array = [[0,1,2],[3,4,5],[6,7,8]]`

which I want to map to a result that looks like

`new_array = [[0,3,6],[1,4,7],[2,5,8]]`

Basically I just need to re-group the first index of each array into its own array, the same for the second and so on.

I feel like there might be a more straightforward way to do this but I can't seem to find anything. For the time being, the best I've come up with is

`new_array = []`

original_array.map { |i, j, k|

new_array << i

new_array << j

new_array << k

}

Any thoughts on how to simplify this? Thanks in advance again for any responses, tips on how to make this question clearer, etc.

Answer Source

You're looking for the `transpose`

method.

```
original_array = [[0,1,2],[3,4,5],[6,7,8]]
original_array.transpose
=> [[0, 3, 6], [1, 4, 7], [2, 5, 8]]
```