← All languages
Ruby method of the day
Random

flat_map

Map each element, then flatten the result by one level.

Description

The flat_map method (also aliased as collect_concat) first maps each element using the given block, then flattens the resulting array by one level. It is equivalent to calling map followed by flatten(1), but more efficient as it does both in a single pass.

This is particularly useful when a mapping operation returns arrays and you want a single flat array of all results. Common use cases include extracting nested attributes, generating multiple outputs per input, or processing hierarchical data.

Without a block, flat_map returns an Enumerator. This method is part of the Enumerable module.

Arguments

NameDescriptionOptional
{ |item| ... } A block that returns an array (or value) for each element. No

Example

[[1, 2], [3, 4]].flat_map { |a| a }   # [1, 2, 3, 4]
[1, 2, 3].flat_map { |n| [n, -n] }    # [1, -1, 2, -2, 3, -3]
["hello world", "foo bar"].flat_map { |s| s.split }  # ["hello", "world", "foo", "bar"]

Reference