DEV Community

Discussion on: Level Up Your Ruby Skillz: Working With Arrays

Collapse
 
grsahil20 profile image
Sahil

Additional Bonus for you flatten. Flatten, as name suggests flatten out an array no matter how much nesting level is involved for an array. Below is the example for 3 level nesting

a =  [[1, 2, 3], [4, [5, [6, 7]]]]
b = a.flatten
# b = [1, 2, 3, 4, 5, 6, 7]

Also, you can do a.flatten!, which will overwrite a itself and assign the new value.

a =  [[1, 2, 3], [4, [5, [6, 7]]]]
a.flatten!
# a = [1, 2, 3, 4, 5, 6, 7]