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 arrays arr1 = [1, 2, [3, 4]] arr2 = [[1, 2, 3,], [4, 5, 6]] arr3 = ["a","b",["a", "b", ["a", "b"]]] # flatten the arrays a = arr1.flatten b = arr2.flatten c = arr3.flatten # print out returned values puts "#{a}" puts "#{b}" puts "#{c}"
RELATED TAGS
CONTRIBUTOR
View all Courses