Array#flatten
arr.flatten(depth=nil) -> array Returns:
array · Updated March 13, 2026 · Array Methods arrays flatten enumerable
.flatten returns a new array with all nested arrays recursively collapsed into a single flat array.
Syntax
array.flatten # flatten all levels
array.flatten(1) # flatten only one level deep
array.flatten(2) # flatten two levels deep
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
depth | Integer or nil | nil | How many levels to flatten. nil or negative flattens all levels. |
Examples
Basic usage
nested = [1, [2, 3], [4, [5, 6]]]
nested.flatten
# => [1, 2, 3, 4, 5, 6]
Without arguments, .flatten recursively flattens all nested arrays.
Controlling depth
nested = [1, [2, [3, [4]]]]
nested.flatten(0)
# => [1, [2, [3, [4]]]] # no flattening
nested.flatten(1)
# => [1, 2, [3, [4]]] # flatten one level
nested.flatten(2)
# => [1, 2, 3, [4]] # flatten two levels
Passing an integer controls how many levels of nesting to collapse.
Common Patterns
Converting tree structures to lists
tree = [1, [2, [3, [4, [5]]]]]
tree.flatten
# => [1, 2, 3, 4, 5]
Flattening after mapping
matrix = [[1, 2], [3, 4], [5, 6]]
matrix.map { |row| row.map { |n| n * 2 } }.flatten
# => [2, 4, 6, 8, 10, 12]
Handling mixed data
mixed = [1, [2, 3], {a: 1}, [4, [5]]]
mixed.flatten
# => [1, 2, 3, {:a=>1}, 4, 5]