Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
flatten
array
communitycreator

How to flatten multi-dimensional arrays into one in Ruby

okwudili onyejiaku

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}"
Array flatten() Function

RELATED TAGS

ruby
flatten
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring