Ruby inner flatten (array of arrays)

后端 未结 2 1998
逝去的感伤
逝去的感伤 2021-01-21 06:42

I have an array like the following

[
  [[0, :a], [2, :b]],
  [3, :c],
  [4, :d],
  [[5, :e], [6, :f], [7, :g]]
]

That is, an Array of elements

相关标签:
2条回答
  • 2021-01-21 06:50

    One way to do is:

    array.flatten.each_slice(2).to_a
    
    0 讨论(0)
  • 2021-01-21 06:56

    Posting another solution here for posterity:

    array.flat_map{|el| el.first.is_a?(Array) ? el : [el]}
    

    This solution also handles if the innermost Arrays are of variable length -- that is, the total Array is an Array of (1) n-element Arrays or (2) Arrays of n-element Arrays, where n is not necessarily the same for any given element. For example

    [
      [1,2,3],
      [[4,5], [6,7,8,9]]
    ]
    
    0 讨论(0)
提交回复
热议问题