instance method
Hash#flatten
() -> ::Array[K | V]
(1 level) -> ::Array[K | V]
(::Integer level) -> ::Array[untyped]
flatten(depth = 1) → new_array
hash.c
View on GitHub ↗
static VALUE
rb_hash_flatten(int argc, VALUE *argv, VALUE hash)
{
VALUE ary;
rb_check_arity(argc, 0, 1);
if (argc) {
int level = NUM2INT(argv[0]);
if (level == 0) return rb_hash_to_a(hash);
ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
rb_hash_foreach(hash, flatten_i, ary);
level--;
if (level > 0) {
VALUE ary_flatten_level = INT2FIX(level);
rb_funcallv(ary, id_flatten_bang, 1, &ary_flatten_level);
}
else if (level < 0) {
/* flatten recursively */
rb_funcallv(ary, id_flatten_bang, 0, 0);
}
}
else {
ary = rb_ary_new_capa(RHASH_SIZE(hash) * 2);
rb_hash_foreach(hash, flatten_i, ary);
}
return ary;
}
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.