How to Flatten an Array in Ruby?

Find out how to flatten an array in ruby regardless of depth

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]]]

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