How can I transpose different sized ruby arrays?

前端 未结 3 1366
萌比男神i
萌比男神i 2020-12-17 22:38

I have an array:

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

I have the following code:

arr.transpose 

but it doesn\'t work,

3条回答
  •  感动是毒
    2020-12-17 23:01

    Using zip as in Stefan's answer is the most straightforward, but if you insist on using transpose, then:

    l = arr.map(&:length).max
    arr.map{|e| e.values_at(0...l)}.transpose
    # => [[1, 4, 6], [2, 5, nil], [3, nil, nil]]
    

    Or without using either:

    Array.new(arr.map(&:length).max){|i| arr.map{|e| e[i]}}
    # => [[1, 4, 6], [2, 5, nil], [3, nil, nil]]
    

提交回复
热议问题