flatten
flatten takes lists inside lists and spreads them into one plain list, like emptying small boxes into one big tray. It removes the extra layers.
In this page:
Syntax
nested.flatten
nested.flatten(depth)
flatten
flatten collapses a nested array of arrays into a single flat array, recursively by default. Passing a depth argument, like flatten(1), limits how many levels of nesting are collapsed.
This is commonly needed after operations like map that can produce arrays-of-arrays.
Note:
flatten(1) flattens only one level deep, useful when you want to preserve some nested structure.
Example: flatten
nested = [1, [2, 3, [4, 5]], 6]
puts nested.flatten.inspect
puts nested.flatten(1).inspect
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Expecting
flattento change the array, when it returns a new one unless you useflatten!. - Forgetting that
flattengoes fully deep by default, soflatten(1)is needed to flatten only one level. - Flattening an array of hashes and expecting the hashes to open, when only arrays are flattened.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: