/ Tags: RUBY-CODE / Categories: SOLUTIONS

Flatten A Deeply Nested Array In Ruby

Arrays in Ruby can be nested arbitrarily deep — arrays of arrays of arrays. flatten collapses them into a single level, but knowing when to flatten fully versus partially is what separates clean code from accidental data loss.

Description

Ruby’s Array#flatten without arguments collapses all nesting into a flat array. flatten(n) collapses only n levels deep, preserving deeper nesting. This distinction matters when your data structure has intentional nesting you want to preserve at certain depths. flat_map is the idiomatic alternative when you’re mapping and flattening in the same operation — it’s both more efficient and more expressive than calling .map { ... }.flatten(1).

Sample input:

  nested = [1, [2, 3], [4, [5, 6]], [7, [8, [9]]]]


Sample Output:

  # flatten fully
  [1, 2, 3, 4, 5, 6, 7, 8, 9]

  # flatten 1 level
  [1, 2, 3, 4, [5, 6], 7, [8, [9]]]

  # flatten 2 levels
  [1, 2, 3, 4, 5, 6, 7, 8, [9]]

Answer

  nested = [1, [2, 3], [4, [5, 6]], [7, [8, [9]]]]

  nested.flatten       # => [1, 2, 3, 4, 5, 6, 7, 8, 9]
  nested.flatten(1)    # => [1, 2, 3, 4, [5, 6], 7, [8, [9]]]
  nested.flatten(2)    # => [1, 2, 3, 4, 5, 6, 7, 8, [9]]

  # flat_map — map + flatten(1) in one pass
  [[1, 2], [3, 4], [5]].flat_map { |arr| arr.map { |n| n * 2 } }
  # => [2, 4, 6, 8, 10]

Learn More

cdrrazan

Rajan Bhattarai

Full Stack Software Developer! 💻 🏡 Grad. Student, MCS. 🎓 Class of '23. GitKraken Ambassador 🇳🇵 2021/22. Works with Ruby / Rails. Photography when no coding. Also tweets a lot at TW / @cdrrazan!

Read More