How to Use the flatten Method in Ruby
In this article, you will learn how to use the flatten method in Ruby.
The flatten Method
The flatten method in Ruby is used to convert a multi-dimensional array into a one-dimensional array. This method returns a new array that contains all the elements of the original array and its sub-arrays, in a single dimension.
Here is an example of how to use the flatten method in Ruby:
arr = [1, 2, [3, 4], [5, 6, [7, 8]]] flatten_arr = arr.flatten puts flatten_arr.inspect
In the above example, the arr array contains two sub-arrays. The flatten method is used to convert the arr array into a one-dimensional array called flatten_arr. The output of this code will be:
[1, 2, 3, 4, 5, 6, 7, 8]
As you can see, the flatten method has taken all the elements of the original array and its sub-arrays, and combined them into a single array.
The flatten method also accepts an optional argument, which specifies the depth to which the array should be flattened. For example, if you have a multi-dimensional array with nested sub-arrays, you can specify how many levels of nesting you want to flatten. Here is an example:
arr = [1, 2, [3, 4], [5, 6, [7, 8]]] flatten_arr = arr.flatten(1) puts flatten_arr.inspect
In this example, the flatten method is called with an argument of 1, which means that only the top-level arrays should be flattened. The output of this code will be:
[1, 2, 3, 4, 5, 6, [7, 8]]
As you can see, the flatten method has only flattened the top-level arrays, and the nested sub-array [7, 8] is still a sub-array in the flattened array.