method
flatten
v1_8_6_287 -
Show latest stable
- Class:
Array
flatten()public
Returns a new array that is a one-dimensional flattening of this array (recursively). That is, for every element that is an array, extract its elements into the new array.
s = [ 1, 2, 3 ] #=> [1, 2, 3] t = [ 4, 5, 6, [7, 8] ] #=> [4, 5, 6, [7, 8]] a = [ s, t, 9, 10 ] #=> [[1, 2, 3], [4, 5, 6, [7, 8]], 9, 10] a.flatten #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10
1Note
Make your custom enumerable "flattenable"
Just alias +to_a+ to +to_ary+
class A
include Enumerable
def each
yield "a"
yield "b"
end
end
[A.new, A.new].flatten => [#<A:0x00007fbddf1b5d88>, #<A:0x00007fbddf1b5d60>]
class A
def to_ary
to_a
end
end
[A.new, A.new].flatten => ["a", "b", "a", "b"]