Flattening a Multi-dimensional array means transforming it into a one-dimensional array. The method used to arrive at this is the flatten!
method.
However, flatten!
will not modify the original array or the array that calls the function. It will only return the expected one-dimensional array.
With
flatten!
the original array is changed permanently.
array.flatten!
This method doesn’t take any parameters.
The value returned is a new one-dimensional array.
In the code below, we shall demonstrate the use of the flatten!
method. We created some multi-dimensional arrays and flattened them permanently.
# create arraysarr1 = [1, 2, [3, 4]]arr2 = [[1, 2, 3,], [4, 5, 6]]arr3 = ["a","b",["a", "b", ["a", "b"]]]# print original arraysputs "#{arr1}"puts "#{arr2}"puts "#{arr3}"# flatten the arraysa = arr1.flatten!b = arr2.flatten!c = arr3.flatten!# print out returned valuesputs "#{a}"puts "#{b}"puts "#{c}"
As seen above, the original arrays were changed.