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

learn how to flatten a deep-nested Ruby array "n" levels 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]]]]

Hope you found this post useful. It was published . Please show your love and support by sharing this post.