0

I have an array of arrays like the following:

=> [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]

I want to rearrange it by order of elements in the inner array, e.g.:

=> [[1,6,11],[2,7,12],[3,8,13],[4,9,14],[5,10,15]]

How can I achieve this?

I know I can iterate an array of arrays like

array1.each do |bla,blo|
  #do anything
end

But the side of inner arrays isn't fixed.

3
  • What should happen when an inner array is a different size? Should nil be inserted in the transposed arrays for shorter inner arrays? Commented Feb 22, 2013 at 23:19
  • I'm sorry, I wasn't completely clear. Inner array doesn't have a fixed size, but they all always have the same size. Commented Feb 22, 2013 at 23:26
  • 1
    ok, I understand. If they are all always the same size, transpose is the way to go. Commented Feb 22, 2013 at 23:31

2 Answers 2

3
p [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]].transpose
#=> [[1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9, 14], [5, 10, 15]]
Sign up to request clarification or add additional context in comments.

Comments

2

use transpose method on Array

a = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
a.transpose
#=> [[1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9, 14], [5, 10, 15]]

Note that this only works if the arrays are of all the same length.

If you want to handle transposing arrays that have different lengths to each other, something like this should do it

class Array
  def safe_transpose
    max_size = self.map(&:size).max
    self.dup.map{|r| r << nil while r.size < max_size; r}.transpose
  end
end

and will yield the following

a = [[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15,16]]
a.safe_transpose
#=> [[1, 6, 11], [2, 7, 12], [3, 8, 13], [4, 9, 14], [5, 10, 15], [nil, nil, 16]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.