Ruby Tuesday – Array#flatten

Today’s Ruby Tuesday is Array#flatten.

Array#flatten returns a new array that has been recursively flattened into a one dimensional array.

a = [1, [:a, :b, :c], 3]
# [1, [:a, :b, :c], 3]
b = a.flatten
# [1, :a, :b, :c, 3]
b
# [1, :a, :b, :c, 3]
a
# [1, [:a, :b, :c], 3]

c = [1, [2, [3, 4, [5 ,6]]]]
# [1, [2, [3, 4, [5, 6]]]]
d = c.flatten
# [1, 2, 3, 4, 5, 6]
c
# [1, [2, [3, 4, [5, 6]]]]
d
# [1, 2, 3, 4, 5, 6]

[1, 2, 3].flatten
# [1, 2, 3]

Ruby also provides a method #flatten! which mutates the state of the object if you happen to require that behavior. And note, that calling flatten! on an array will return nil if the array was not modified.

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

[1, 2, 3].flatten!
# nil

–Proctor