Ruby Flatten

Write a summary describing how the method you chose works, and give a brief example of how to use it

The .flatten method provides an easy way to convert multi-dimensional arrays to one-dimensional array. Here is a basic example.

arr = [[1, 2, 3, 4], [5, 6, 7]]
arr.flatten #=> [1, 2, 3, 4, 5, 6, 7]

The .flatten method works recursively through the array until the array is no longer multi-dimensional. This behavior can be modified through an optional argument. By passing in a numerical level parameter, .flatten will be told to stop after a certain number of levels of recursion.

In the following example, the array arr goes four levels deep. Note how the increase in the number passed to flatten changes the output.

arr = [[["a", "b", "c", "d"]], [[["e", "f", "g", "h"]], "j", "k"]]
arr.flatten(1) #=>[["a", "b", "c", "d"], [["e", "f", "g", "h"]], "j", "k"]
arr.flatten(2) #=>["a", "b", "c", "d", ["e", "f", "g", "h"], "j", "k"]
arr.flatten(3) #=>["a", "b", "c", "d", "e", "f", "g", "h", "j", "k"]
Previous
Previous

Fibonacci Numbers