Skip to content
instance method

Array#flatten!

(?::int level) -> self?
flatten!(depth = nil) → self or nil

Returns self as a recursively flattening of self to depth levels of recursion; depth must be an integer-convertible object, or nil. At each level of recursion:

  • Each element that is an array is “flattened” (that is, replaced by its individual array elements).

  • Each element that is not an array is unchanged (even if the element is an object that has instance method flatten).

Returns nil if no elements were flattened.

With non-negative integer argument depth, flattens recursively through depth levels:

Example
a = [ 0, [ 1, [2, 3], 4 ], 5, {foo: 0}, Set.new([6, 7]) ]
a                   # => [0, [1, [2, 3], 4], 5, {:foo=>0}, #<Set: {6, 7}>]
a.dup.flatten!(1)   # => [0, 1, [2, 3], 4, 5, {:foo=>0}, #<Set: {6, 7}>]
a.dup.flatten!(1.1) # => [0, 1, [2, 3], 4, 5, {:foo=>0}, #<Set: {6, 7}>]
a.dup.flatten!(2)   # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]
a.dup.flatten!(3)   # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]

With nil or negative argument depth, flattens all levels:

Example
a.dup.flatten!     # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]
a.dup.flatten!(-1) # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]

Related: Array#flatten; see also Methods for Assigning.

See also #flatten #freeze #first #hash also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0