Array#flatten_map
Added in v2.5 · Updated March 13, 2026 · Array Methods
ruby array-methods enumerable
.flat_map combines the operations of .map and .flatten(1) into a single method. It transforms each element with a block, then flattens the results by one level. This is more efficient than chaining .map followed by .flatten because it avoids creating an intermediate array.
numbers = [1, 2, 3]
# map then flatten - two operations
numbers.map { |n| [n, n * 2] }.flatten
# => [1, 2, 2, 4, 3, 6]
# flat_map - one operation
numbers.flat_map { |n| [n, n * 2] }
# => [1, 2, 2, 4, 3, 6]
Syntax
array.flat_map { |element| block }
array.flat_map do |element|
# block body
end
Without a block, .flat_map returns an Enumerator.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| block | Block | Required | Code to run for each element. The return value is flattened by one level. |
Return Value
Returns a new array with each element transformed by the block, flattened by one level.
Examples
Basic transformation
[1, 2, 3].flat_map { |n| [n, n * 10] }
# => [1, 10, 2, 20, 3, 30]
# Each element produces an array, which gets flattened
words = ["hello", "world"]
words.flat_map { |word| word.chars }
# => ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]
Working with nested arrays
matrix = [[1, 2], [3, 4], [5, 6]]
# map preserves the nested structure
matrix.map { |row| row.map { |n| n * 2 } }
# => [[2, 4], [6, 8], [10, 12]]
# flat_map flattens one level
matrix.flat_map { |row| row.map { |n| n * 2 } }
# => [2, 4, 6, 8, 10, 12]
With hashes
data = [{a: 1, b: 2}, {c: 3, d: 4}]
data.flat_map { |hash| hash.to_a }
# => [[:a, 1], [:b, 2], [:c, 3], [:d, 4]]
# Returns flat array of key-value pairs
Using without block
enum = [1, 2, 3].flat_map
# => #<Enumerator: [1, 2, 3]:flat_map>
enum.each { |n| [n, -n] }
# => [1, -1, 2, -2, 3, -3]
Performance
.flat_map is more efficient than .map { }.flatten:
# Less efficient - creates intermediate array
large_array.map { |e| [e] }.flatten
# More efficient - single pass
large_array.flat_map { |e| [e] }
The efficiency gain comes from avoiding the intermediate array allocation. For small arrays the difference is negligible, but it matters for large datasets.
Common Patterns
Splitting strings
sentences = ["hello world", "foo bar"]
sentences.flat_map { |s| s.split }
# => ["hello", "world", "foo", "bar"]
Expanding pairs
pairs = [[1, 2], [3, 4], [5, 6]]
pairs.flat_map { |a, b| [a * 2, b * 2] }
# => [2, 4, 6, 8, 10, 12]
With lazy enumeration
require 'lazy'
(1..Float::INFINITY).lazy.flat_map { |n| [n, n] }.first(6)
# => [1, 1, 2, 2, 3, 3]
Alias
.collect_concat is an alias for .flat_map. Use whichever reads better in context:
# Both are equivalent
array.flat_map { |e| [e] }
array.collect_concat { |e| [e] }
See Also
.map— Transform elements without flattening.flatten— Flatten nested arrays (all levels)- Enumerable#collect_concat docs — Alias for flat_map