instance method
Array#flatten!
(?::int level) -> self?
flatten!(depth = nil) → self or nil
array.c
View on GitHub ↗
static VALUE
rb_ary_flatten_bang(int argc, VALUE *argv, VALUE ary)
{
int mod = 0, level = -1;
VALUE result, lv;
lv = (rb_check_arity(argc, 0, 1) ? argv[0] : Qnil);
rb_ary_modify_check(ary);
if (!NIL_P(lv)) level = NUM2INT(lv);
if (level == 0) return Qnil;
result = flatten(ary, level);
if (result == ary) {
return Qnil;
}
if (!(mod = ARY_EMBED_P(result))) rb_ary_freeze(result);
rb_ary_replace(ary, result);
if (mod) ARY_SET_EMBED_LEN(result, 0);
return ary;
}
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.