Array.flatten
Returns a new one-dimensional array by recursively flattening nested arrays.
array.flatten -> new_arrayThis static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.
What it does
Overview
Returns a new one-dimensional array by recursively flattening nested arrays.
The `Array.flatten` method is used to convert a multi-dimensional array (an array containing other arrays) into a single-dimensional array. It recursively traverses all nested arrays and extracts their elements, placing them into a new, flat array. By default, `flatten` will flatten all levels of nesting. You can optionally pass an integer argument `level` to `flatten` to specify how many levels deep the flattening should occur. This is particularly useful when working with data structures that involve nested collections, such as parsing JSON or processing tree-like data. `flatten` is a non-destructive method; it returns a new array and leaves the original array unchanged. To modify the array in place, use `flatten!`. It's a powerful tool for simplifying complex array structures into a more manageable linear form.
Quick reference
Syntax
array.flatten -> new_array
Inputs
Parameters
See it in practice
Examples
Flattening a simple nested array
nested_array = [1, [2, 3], 4, [5, [6, 7]]]
flat_array = nested_array.flatten
puts "Original: #{nested_array}"
puts "Flattened: #{flat_array}"Original: [1, [2, 3], 4, [5, [6, 7]]] Flattened: [1, 2, 3, 4, 5, 6, 7]
The `flatten` method recursively extracts all elements from nested arrays, creating a single-dimensional array.
Flattening to a specific level
deep_nested = [1, [2, [3, 4]], [5, [6, [7]]]]
flattened_one_level = deep_nested.flatten(1)
flattened_two_levels = deep_nested.flatten(2)
puts "Original: #{deep_nested}"
puts "Flattened 1 level: #{flattened_one_level}"
puts "Flattened 2 levels: #{flattened_two_levels}"Original: [1, [2, [3, 4]], [5, [6, [7]]]] Flattened 1 level: [1, 2, [3, 4], 5, [6, [7]]] Flattened 2 levels: [1, 2, 3, 4, 5, 6, [7]]
Passing an integer `level` argument to `flatten` controls how many levels of nesting are removed.
Flattening with mixed data types
mixed_array = [1, "hello", [2, true], {a: 3, b: 4}, [nil, 5]]
flat_mixed = mixed_array.flatten
puts "Original: #{mixed_array}"
puts "Flattened: #{flat_mixed}"Original: [1, "hello", [2, true], {:a=>3, :b=>4}, [nil, 5]] Flattened: [1, "hello", 2, true, {:a=>3, :b=>4}, nil, 5]
`flatten` works with arrays containing various data types, including numbers, strings, booleans, hashes, and `nil`. Hashes themselves are not flattened further.
Debug faster
Common Errors
Modifying original array unintentionally
Cause: Expecting `flatten` to modify the array in place.
Fix: `flatten` returns a *new* array. If you want to modify the original array, use `flatten!` (with a bang `!`).
arr = [1, [2, 3]]
arr.flatten # Returns [1, 2, 3], but arr is still [1, [2, 3]]
puts arr # Output: [1, [2, 3]]
# Fix:
arr.flatten!
puts arr # Output: [1, 2, 3]Unexpected flattening of non-array objects
Cause: `flatten` only flattens arrays. Other enumerable objects (like hashes) are treated as single elements and not recursively flattened unless they contain arrays.
Fix: Understand that `flatten` specifically targets arrays. If you need to extract values from nested hashes, you'll need to iterate or use other methods like `values` or `map`.
arr = [1, {a: [2, 3]}, 4]
flat_arr = arr.flatten
puts flat_arr # Output: [1, {:a=>[2, 3]}, 4] (the hash itself is not flattened)
# If you wanted to flatten values from hash too:
# flat_arr_with_hash_values = arr.flat_map { |e| e.is_a?(Hash) ? e.values.flatten : e }
# puts flat_arr_with_hash_values # Output: [1, [2, 3], 4]Performance on extremely deep arrays
Cause: Recursively flattening extremely deep arrays can lead to stack overflow errors or performance issues due to deep recursion.
Fix: For very deep or untrusted nested structures, consider processing them iteratively or setting a `level` limit to prevent excessive recursion.
# This could cause a stack overflow for very large N
# def create_deep_array(n); n == 0 ? 1 : [create_deep_array(n-1)]; end
# deep_arr = create_deep_array(10000)
# deep_arr.flattenRuntime support
Compatibility
Source: Ruby-Doc.org
Common questions
Frequently Asked Questions
Returns a new one-dimensional array by recursively flattening nested arrays.
level: The number of levels to flatten. If omitted, all levels are flattened.
Modifying original array unintentionally: `flatten` returns a *new* array. If you want to modify the original array, use `flatten!` (with a bang `!`). Unexpected flattening of non-array objects: Understand that `flatten` specifically targets arrays. If you need to extract values from nested hashes, you'll need to iterate or use other methods like `values` or `map`. Performance on extremely deep arrays: For very deep or untrusted nested structures, consider processing them iteratively or setting a `level` limit to prevent excessive recursion.