Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I transpose different sized ruby arrays?

I have an array:

arr=[[1,2,3],[4,5],[6]],

I have the following code:

arr.transpose 

but it doesn't work,how to solve it?

I am getting

 [[1,2,3],[4,5],[6]].transpose
IndexError: element size differs (2 should be 3)
    from (irb):13:in `transpose'
    from (irb):13
    from /home/durrant

my solution:

arr.reduce(&:zip).map(&:flatten)

output:

[[1, 4, 6], [2, 5, nil], [3, nil, nil]]
like image 523
bluexuemei Avatar asked Sep 24 '14 12:09

bluexuemei


1 Answers

If the length of the subarrays don’t match, an IndexError is raised.

irb(main):002:0> arr=[[1,2,3],[4,5],[6]]
=> [[1, 2, 3], [4, 5], [6]]
irb(main):003:0> arr.transpose
IndexError: element size differs (2 should be 3)
    from (irb):3:in `transpose'
    from (irb):3
    from /Users/liuxingqi/.rvm/rubies/ruby-2.1.2/bin/irb:11:in `<main>'

should be:

irb(main):004:0> arr=[[1,2,3],[4,5,6]]
=> [[1, 2, 3], [4, 5, 6]]
irb(main):005:0> arr.transpose
=> [[1, 4], [2, 5], [3, 6]]

or

irb(main):006:0> arr=[[1,2],[3,4],[5,6]]
=> [[1, 2], [3, 4], [5, 6]]
irb(main):007:0> arr.transpose
=> [[1, 3, 5], [2, 4, 6]]
like image 152
pangpang Avatar answered Oct 24 '22 20:10

pangpang