Flowdock
flatten(*args) public

Returns a new array that is a one-dimensional flattening of self (recursively).

That is, for every element that is an array, extract its elements into the new array.

The optional level argument determines the level of recursion to flatten.

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]
a = [ 1, 2, [3, [4, 5] ] ]
a.flatten(1)              #=> [1, 2, 3, [4, 5]]
Show source
Register or log in to add new notes.
May 5, 2020
0 thanks

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"]