Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 42 / 68

Flattening an Array

In this lesson you will learn to flatten a nested array with Ruby's flatten method. This is for anyone searching for "Ruby flatten how to use".

Expanding an array that contains other arrays into one flat array is called flattening. Ruby has a method named exactly that: .flatten.

The sample code calls .flatten on the multiply-nested [1, [2, 3], [4, [5, 6]]] and gets a fully flat array back. Notice that what other languages need a hand-written recursive function for takes a single method here.

A common stumbling block for beginners is how to limit the depth. Passing an argument, as in .flatten(1), flattens only one level; by default every level is flattened.

There is also flat_map, which does map and flatten in one go. Flattening is a useful technique whenever you want to treat nested data as one list.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)