How to permanently flatten a multidimensional array in Ruby

Overview

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.

Syntax

array.flatten!

Parameters

This method doesn’t take any parameters.

Return value

The value returned is a new one-dimensional array.

Code sample

In the code below, we shall demonstrate the use of the flatten! method. We created some multi-dimensional arrays and flattened them permanently.

# create arrays
arr1 = [1, 2, [3, 4]]
arr2 = [[1, 2, 3,], [4, 5, 6]]
arr3 = ["a","b",["a", "b", ["a", "b"]]]
# print original arrays
puts "#{arr1}"
puts "#{arr2}"
puts "#{arr3}"
# flatten the arrays
a = arr1.flatten!
b = arr2.flatten!
c = arr3.flatten!
# print out returned values
puts "#{a}"
puts "#{b}"
puts "#{c}"

As seen above, the original arrays were changed.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources