How to Flatten an Array in Ruby?

You can flatten an array in Ruby using the Array#flatten method, for example, like so:

print [1, [2, 3], [4, [5, 6, [7, 8]]]].flatten
#=> [1, 2, 3, 4, 5, 6, 7, 8]

It is also possible to flatten the array only "n-level" deep by specifying the (optional) depth number as an argument to the method. For example, the following would flatten the array only one-level deep:

print [1, [2, 3], [4, [5, 6, [7, 8]]]].flatten(1)
#=> [1, 2, 3, 4, [5, 6, [7, 8]]]

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.