0
0
Rubyprogramming~5 mins

Flat_map for nested flattening in Ruby

Choose your learning style9 modes available
Introduction
Flat_map helps you turn a list of lists into a single list by combining all inner lists into one. It makes nested data easier to work with.
You have a list of groups and want one list of all items.
You want to simplify nested arrays into a flat array.
You want to apply a transformation and flatten the result in one step.
You want to avoid writing extra loops to flatten nested data.
Syntax
Ruby
array.flat_map { |element| block }
The block returns an array for each element.
flat_map combines all returned arrays into one flat array.
Examples
Flattens the nested arrays into one array: [1, 2, 3, 4]
Ruby
[[1, 2], [3, 4]].flat_map { |a| a }
For each number, creates an array with the number and its double, then flattens: [1, 2, 2, 4, 3, 6]
Ruby
[1, 2, 3].flat_map { |n| [n, n * 2] }
Sample Program
This program takes a nested list of fruits and vegetables and flattens it into one list.
Ruby
nested = [["apple", "banana"], ["carrot", "date"], ["egg"]]
flat = nested.flat_map { |group| group }
puts flat.inspect
OutputSuccess
Important Notes
flat_map is like map followed by flatten(1), but faster and cleaner.
Use flat_map when your block returns arrays and you want one flat array.
If your block returns single values, flat_map works like map.
Summary
flat_map flattens one level of nested arrays after mapping.
It simplifies working with nested lists by combining mapping and flattening.
Use it to get a single list from nested lists easily.