Array#flatten!
array.flatten!(level=nil) -> array or nil Returns:
Array or nil · Updated March 13, 2026 · Array Methods arrays mutation nested flattening
The flatten! method transforms a nested array structure into a single flat array, modifying the original array in place. It recursively flattens all sub-arrays until the array is one-dimensional.
How It Works
flatten! takes an optional depth parameter. Without arguments, it flattens all levels of nesting. With a depth, it only flattens that many levels.
Practical Examples
Basic Flattening
# Simple nested array
array = [1, [2, 3], [4, [5, 6]]]
array.flatten!
puts array.inspect # => [1, 2, 3, 4, 5, 6]
# Flattens all levels completely
nested = [[1, 2], [[3, 4]], [[[5]]]]
nested.flatten! # => [1, 2, 3, 4, 5]
With Depth Parameter
# Flatten only one level
data = [1, [2, 3], [[4, 5]]]
data.flatten!(1)
# => [1, 2, 3, [4, 5]] - inner array preserved
# Depth of 0 returns copy of original
original = [1, [2, 3]]
copy = original.flatten!(0)
# => [1, [2, 3]]
Practical Data Processing
# Combine multiple groups of items
groups = [[1, 2], [3, 4], [5, 6]]
groups.flatten! # => [1, 2, 3, 4, 5, 6]
# Process tree-structured data
tree = [:root, [:child1, :child2], [:child3, [:grandchild]]]
tree.flatten! # => [:root, :child1, :child2, :child3, :grandchild]
Returns nil When No Change Needed
# Already flat array returns nil
flat = [1, 2, 3]
result = flat.flatten!
puts result # => nil
# Bang methods return nil when no modification needed
# This is useful for checking if flattening occurred
array = [1, 2, 3]
if array.flatten!
puts "Array was flattened"
else
puts "Already flat"
end
Comparison with flatten (non-destructive)
# flatten returns a new array
original = [1, [2, 3]]
new_array = original.flatten
puts original # => [1, [2, 3]] (unchanged)
puts new_array # => [1, 2, 3]
# flatten! modifies in place
original.flatten!
puts original # => [1, 2, 3] (modified)
Working with Mixed Data
# Flattens arrays but leaves non-arrays untouched
mixed = [1, "hello", [2, 3], {key: "value"}]
mixed.flatten! # => [1, "hello", 2, 3, {:key=>"value"}]
Performance Considerations
For very deep arrays, flatten! can be memory-intensive. If you need lazy flattening, consider using a loop or recursion that processes elements one at a time.