How to flatten multi-dimensional arrays into one in Ruby

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.

Syntax

array.flatten

Parameters

This method takes no parameters.

Return value

A new array is returned that is one-dimensional.

Code example

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}"

Free Resources