Sha256: 4d42a7a43a1579d4d13cabeb09db30a6219eab7c99c5d5ad74ee3c76364493e9

Contents?: true

Size: 1.39 KB

Versions: 47

Compression:

Stored size: 1.39 KB

Contents

unless ([[]].flatten(1) rescue false)
  require 'backports/tools/alias_method_chain'
  require 'backports/tools/arguments'

  class Array
    # Recursively flatten any contained Arrays into an one-dimensional result.
    # Adapted from rubinius'
    def flatten_with_optional_argument(level=-1)
      dup.flatten!(level) || self
    end

    # Flattens self in place as #flatten. If no changes are
    # made, returns nil, otherwise self.
    # Adapted from rubinius'
    def flatten_with_optional_argument!(level=-1)
      level = Backports.coerce_to_int(level)
      return flatten_without_optional_argument! if level < 0

      out = []
      ret = recursively_flatten_finite(self, out, level)
      replace(out) if ret
      ret
    end

    Backports.alias_method_chain self, :flatten, :optional_argument
    Backports.alias_method_chain self, :flatten!, :optional_argument

    # Helper to recurse through flattening
    # Adapted from rubinius'; recursion guards are not needed because level is finite
    def recursively_flatten_finite(array, out, level)
      ret = nil
      if level <= 0
        out.concat(array)
      else
        array.each do |o|
          if ary = Backports.is_array?(o)
            recursively_flatten_finite(ary, out, level - 1)
            ret = self
          else
            out << o
          end
        end
      end
      ret
    end
    private :recursively_flatten_finite
  end
end

Version data entries

47 entries across 47 versions & 4 rubygems

Version Path
backports-3.25.0 lib/backports/1.8.7/array/flatten.rb
backports-3.24.1 lib/backports/1.8.7/array/flatten.rb
backports-3.24.0 lib/backports/1.8.7/array/flatten.rb
backports-3.23.0 lib/backports/1.8.7/array/flatten.rb
backports-3.22.1 lib/backports/1.8.7/array/flatten.rb
backports-3.22.0 lib/backports/1.8.7/array/flatten.rb
backports-3.21.0 lib/backports/1.8.7/array/flatten.rb
backports-3.20.2 lib/backports/1.8.7/array/flatten.rb
backports-3.20.1 lib/backports/1.8.7/array/flatten.rb
backports-3.20.0 lib/backports/1.8.7/array/flatten.rb
backports-3.19.0 lib/backports/1.8.7/array/flatten.rb
backports-3.18.2 lib/backports/1.8.7/array/flatten.rb
backports-3.18.1 lib/backports/1.8.7/array/flatten.rb
backports-3.18.0 lib/backports/1.8.7/array/flatten.rb
files.com-1.0.55 docs/vendor/bundle/ruby/2.5.0/gems/backports-3.12.0/lib/backports/1.8.7/array/flatten.rb
backports-3.17.2 lib/backports/1.8.7/array/flatten.rb
backports-3.17.1 lib/backports/1.8.7/array/flatten.rb
backports-3.17.0 lib/backports/1.8.7/array/flatten.rb
backports-3.16.1 lib/backports/1.8.7/array/flatten.rb
backports-3.16.0 lib/backports/1.8.7/array/flatten.rb