flatten removes nesting, while compact removes nil values. They solve different problems and are often chained.
flattenturns nested arrays into one flat array, at every depth by default. Pass a depth to stop early, so[[1, [2]]].flatten(1)gives[1, [2]].compactreturns a copy without thenilelements. It keepsfalseand empty strings, because onlynilis removed.
When a map block returns arrays, flat_map maps and flattens one level in a single step.
Both return a new array. The bang versions flatten! and compact! change the array in place and return nil when nothing changed.
[[1, 2], [3, [4]]].flatten # [1, 2, 3, 4]
[1, nil, 2, nil, 3].compact # [1, 2, 3]
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓