How to Flatten an Array in Ruby Only "n-level" Deep?

In Ruby, you can simply use the Array#flatten method to flatten an array. If you use it without any arguments, then by default it will flatten an array down to the deepest level recursively. However, if you wish to flatten an array only "n-level" deep, then you can do so by specifying the (optional) depth number as an argument to the method:

Array.flatten(depth)

For example, to only flatten an array 1-level deep, you would do the following:

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

Similarly, to flatten an array 2-levels deep, you would do the following:

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

It is also possible to pass 0 as the depth. However, doing so will leave the array unchanged:

print [1, [2, 3], [4, [5, 6, [7, 8]]]].flatten(0)
#=> [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.