How to Use flat_map in Ruby: Syntax and Examples
In Ruby,
flat_map is used to map each element of a collection to a new array and then flatten the result by one level. It combines map and flatten(1) in one step, making it useful for transforming nested arrays into a single flat array.Syntax
The flat_map method is called on an enumerable and takes a block. For each element, the block returns an array or enumerable. flat_map then concatenates all these arrays into one flat array.
- receiver: The array or enumerable you call
flat_mapon. - block: A block that returns an array or enumerable for each element.
- result: A single flattened array combining all returned arrays.
ruby
collection.flat_map { |element| block }Example
This example shows how flat_map transforms an array of numbers by returning an array of the number and its square, then flattens the result into one array.
ruby
numbers = [1, 2, 3] result = numbers.flat_map { |n| [n, n * n] } puts result.inspect
Output
[1, 1, 2, 4, 3, 9]
Common Pitfalls
A common mistake is using map instead of flat_map when the block returns arrays, which results in a nested array instead of a flat one. Another pitfall is expecting flat_map to flatten deeply nested arrays; it only flattens one level.
ruby
arr = [[1, 2], [3, 4]] # Using map returns nested arrays mapped = arr.map { |sub| sub.map { |n| n * 2 } } puts mapped.inspect # Using flat_map flattens one level flat_mapped = arr.flat_map { |sub| sub.map { |n| n * 2 } } puts flat_mapped.inspect
Output
[[2, 4], [6, 8]]
[2, 4, 6, 8]
Quick Reference
| Method | Description | Example Output |
|---|---|---|
| map | Transforms elements but keeps nested arrays | [[2, 4], [6, 8]] |
| flat_map | Transforms and flattens one level | [2, 4, 6, 8] |
| flatten(1) | Flattens nested arrays by one level | [2, 4, 6, 8] |
Key Takeaways
flat_map combines mapping and flattening one level into a single step.Use
flat_map when your block returns arrays and you want a flat result.flat_map only flattens one level, not deeply nested arrays.Using
map instead of flat_map can cause nested arrays.It is useful for simplifying nested array transformations in Ruby.
