← Back to Ruby Course | Chapter 4: Arrays | Lesson 4 of 7

flatten

flatten takes lists inside lists and spreads them into one plain list, like emptying small boxes into one big tray. It removes the extra layers.

In this page:

  1. flatten
Syntax
ruby
nested.flatten
nested.flatten(depth)

flatten

flatten collapses a nested array of arrays into a single flat array, recursively by default. Passing a depth argument, like flatten(1), limits how many levels of nesting are collapsed.

This is commonly needed after operations like map that can produce arrays-of-arrays.

Note: flatten(1) flattens only one level deep, useful when you want to preserve some nested structure.

Example: flatten

markup
nested = [1, [2, 3, [4, 5]], 6]

puts nested.flatten.inspect
puts nested.flatten(1).inspect
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Expecting flatten to change the array, when it returns a new one unless you use flatten!.
  2. Forgetting that flatten goes fully deep by default, so flatten(1) is needed to flatten only one level.
  3. Flattening an array of hashes and expecting the hashes to open, when only arrays are flattened.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.