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

flatten

In this page:

  1. flatten

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
🔒

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.