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
array.c
View on GitHub ↗
static VALUE
rb_ary_flatten(int argc, VALUE *argv, VALUE ary)
{
int level = -1;
VALUE result;
if (rb_check_arity(argc, 0, 1) && !NIL_P(argv[0])) {
level = NUM2INT(argv[0]);
if (level == 0) return ary_make_shared_copy(ary);
}
result = flatten(ary, level);
if (result == ary) {
result = ary_make_shared_copy(ary);
}
return result;
}
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.