sadie parker
sadie parker

Reputation: 381

How can I map a "square" 2 dimensional array to switch coordinates? (ruby)

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.

Upvotes: 1

Views: 82

Answers (1)

Arun Kumar Mohan
Arun Kumar Mohan

Reputation: 11915

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]]

Check out the docs for more information.

Upvotes: 2

Related Questions