Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

instance method

Array#flatten

(?::int level) -> ::Array[untyped]
flatten(depth = nil) → new_array

Returns a new array that is a recursive 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).

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.flatten(0)   # => [0, [1, [2, 3], 4], 5, {:foo=>0}, #<Set: {6, 7}>]
a.flatten(1  ) # => [0, 1, [2, 3], 4, 5, {:foo=>0}, #<Set: {6, 7}>]
a.flatten(1.1) # => [0, 1, [2, 3], 4, 5, {:foo=>0}, #<Set: {6, 7}>]
a.flatten(2)   # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]
a.flatten(3)   # => [0, 1, 2, 3, 4, 5, {:foo=>0}, #<Set: {6, 7}>]

With nil or negative depth, flattens all levels.

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

Related: Array#flatten!; see also Methods for Converting.

Ruby version changes

  1. 3.0
See also #flatten! #first #find_index #freeze also in 4.1 · 4.0 · 3.3 · 3.2 · 3.1 · 3.0