Search code examples
arraysrubyflattensub-array

Ruby - elegantly flatten an array but don't ignore empty sub-arrays


Using .flatten is a handy little trick to take an array of sub-arrays and turn it into a single array. For example: [[1,3],2,[5,8]].flatten => [1,3,2,5,8] You can even include nil [1,[2,nil],3].flatten will result in [1,2,nil,3].

This kind of method is very useful when nesting a .map method, but how would you account for an empty sub-array? For example: [1,[2,3],[],4].flatten would return [1,2,3,4]... but what if I need to keep track of the empty sub array maybe turn the result into [1,2,3,0,4] or [1,2,3,nil,4]

Is there any elegant way to do this? Or would I need to write some method to iterate through each individual sub-array and check it one by one?


Solution

  • If you don't need to recursively check nested sub-arrays:

    [1,[2,3],[],4].map { |a| a == [] ? nil : a }.flatten