An array that is not one-dimensional can be flattened in Ruby using the flatten
method. It recursively flattens the array and returns a new array that is one-dimensional.
array.flatten
This method takes no parameters.
A new array is returned that is one-dimensional.
In the example below, we will create some dimensional arrays and flatten them to a one-dimensional array using the flatten
method.
# create arraysarr1 = [1, 2, [3, 4]]arr2 = [[1, 2, 3,], [4, 5, 6]]arr3 = ["a","b",["a", "b", ["a", "b"]]]# flatten the arraysa = arr1.flattenb = arr2.flattenc = arr3.flatten# print out returned valuesputs "#{a}"puts "#{b}"puts "#{c}"