Skip to content
instance method

Hash#flatten

() -> ::Array[K | V]
(1 level) -> ::Array[K | V]
(::Integer level) -> ::Array[untyped]
flatten(depth = 1) → new_array

With positive integer depth, returns a new array that is a recursive flattening of self to the given depth.

At each level of recursion:

  • Each element whose value is an array is “flattened” (that is, replaced by its individual array elements); see Array#flatten.

  • Each element whose value is not an array is unchanged. even if the value is an object that has instance method flatten (such as a hash).

Examples; note that entry foo: {bar: 1, baz: 2} is never flattened.

Example
h = {foo: {bar: 1, baz: 2}, bat: [:bam, [:bap, [:bah]]]}
h.flatten(1) # => [:foo, {:bar=>1, :baz=>2}, :bat, [:bam, [:bap, [:bah]]]]
h.flatten(2) # => [:foo, {:bar=>1, :baz=>2}, :bat, :bam, [:bap, [:bah]]]
h.flatten(3) # => [:foo, {:bar=>1, :baz=>2}, :bat, :bam, :bap, [:bah]]
h.flatten(4) # => [:foo, {:bar=>1, :baz=>2}, :bat, :bam, :bap, :bah]
h.flatten(5) # => [:foo, {:bar=>1, :baz=>2}, :bat, :bam, :bap, :bah]

With negative integer depth, flattens all levels:

Example
h.flatten(-1) # => [:foo, {:bar=>1, :baz=>2}, :bat, :bam, :bap, :bah]

With depth zero, returns the equivalent of to_a:

Example
h.flatten(0) # => [[:foo, {:bar=>1, :baz=>2}], [:bat, [:bam, [:bap, [:bah]]]]]

Related: see Methods for Converting.

See also #filter! #hash #filter #has_key? also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0