Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
flatten
array
communitycreator

How to permanently flatten a multidimensional array in Ruby

okwudili onyejiaku

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.

RELATED TAGS

ruby
flatten
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring