Flatten A Nested Array To A Specific Depth In Ruby
Use Array#flatten with a depth argument to collapse nested arrays to a precise level — avoiding full flattening when partial structure needs to be preserved.
Description
Array#flatten without arguments recursively flattens all nested arrays. Pass a depth integer to stop at a specific level: flatten(1) removes one layer of nesting, flatten(2) removes two, and so on.
Use when working with grouped data where outer structure matters — e.g., an array of rows, each row containing values — and full collapse would lose the grouping information.
Sample input:
arr = [1, [2, [3, [4, 5]]], 6]
Sample Output:
# flatten(1) => [1, 2, [3, [4, 5]], 6]
# flatten(2) => [1, 2, 3, [4, 5], 6]
# flatten => [1, 2, 3, 4, 5, 6]
Answer
arr = [1, [2, [3, [4, 5]]], 6]
arr.flatten # => [1, 2, 3, 4, 5, 6] (full flatten)
arr.flatten(1) # => [1, 2, [3, [4, 5]], 6]
arr.flatten(2) # => [1, 2, 3, [4, 5], 6]
arr.flatten(3) # => [1, 2, 3, 4, 5, 6]
# Preserve row grouping but flatten inner values
rows = [[1, [2, 3]], [4, [5, 6]]]
rows.map { |row| row.flatten }
# => [[1, 2, 3], [4, 5, 6]] (flatten each row, keep outer array)
rows.flatten(1)
# => [1, [2, 3], 4, [5, 6]] (removes outer level only)
# In-place variant
arr2 = [1, [2, [3]]]
arr2.flatten!(1) # modifies in place
# arr2 => [1, 2, [3]]
Check viewARU - Brand Newsletter!
Newsletter to DEVs by DEVs - boost your Personal Brand & career! 🚀