How to Flatten an Array in Ruby: Simple Guide
In Ruby, you can flatten a nested array using the
flatten method, which returns a new array with all nested arrays merged into one. Use array.flatten to get a single-level array from any depth of nested arrays.Syntax
The flatten method is called on an array object to convert nested arrays into a single flat array.
array.flatten: Returns a new flattened array without modifying the original.array.flatten!: Flattens the array in place, modifying the original array.
ruby
array = [1, [2, 3], [4, [5, 6]]] flat_array = array.flatten # flat_array is [1, 2, 3, 4, 5, 6]
Example
This example shows how to flatten a nested array using flatten and flatten!. The first returns a new array, the second modifies the original.
ruby
nested = [1, [2, [3, 4]], 5] flat = nested.flatten puts "Flattened (new array): #{flat.inspect}" nested.flatten! puts "Flattened (in place): #{nested.inspect}"
Output
Flattened (new array): [1, 2, 3, 4, 5]
Flattened (in place): [1, 2, 3, 4, 5]
Common Pitfalls
One common mistake is expecting flatten to modify the original array without using the bang version flatten!. Also, flattening very large or deeply nested arrays can affect performance.
ruby
arr = [1, [2, 3]] arr.flatten puts arr.inspect # Output: [1, [2, 3]] (original unchanged) arr.flatten! puts arr.inspect # Output: [1, 2, 3] (original modified)
Output
[1, [2, 3]]
[1, 2, 3]
Quick Reference
| Method | Description |
|---|---|
| flatten | Returns a new flattened array, original unchanged |
| flatten! | Flattens the array in place, modifies original |
| flatten(level) | Flattens array up to specified depth level |
Key Takeaways
Use
flatten to get a new flat array without changing the original.Use
flatten! to flatten the array in place and modify the original.You can specify a depth level with
flatten(level) to flatten partially.Remember
flatten does not change the original array unless you use the bang version.Flattening deeply nested arrays can impact performance, so use wisely.