Sha256: 8279019bdeb890282a69c65c7a51dbc25fc308f2306af41213178aed04d80328

Contents?: true

Size: 1.53 KB

Versions: 3

Compression:

Stored size: 1.53 KB

Contents

module Enumerable

  unless method_defined?(:sum)
    def sum(identity=0)
      inject { |s, e| s + e } || identity
    end
  end

  def average(identity=0)
    collection_size = to_a.size
    collection_size > 0 ? inject(&:+) / collection_size.to_f : identity
  end

  def drop_last(n)
    array = to_a

    return array if n > array.size
    array[0...(array.size - n)]
  end

  def drop_last_while
    return to_enum(:drop_last_while) unless block_given?

    result = []
    dropping = true
    reverse_each do |obj|
      result.unshift(obj) unless dropping &&= yield(obj)
    end
    result
  end

  def exactly?(n)
    found_count = 0

    if block_given?
      each do |*o|
        if yield(*o)
          found_count += 1
        end
      end
    else
      each do |o|
        if o
          found_count += 1
        end
      end
    end

    (found_count > n) ? false : n == found_count
  end

  def frequencies
    each_with_object(Hash.new(0)) { |e, a| a[e] += 1 }
  end

  def several?
    found_count = 0

    if block_given?
      each do |*o|
        if yield(*o)
          found_count += 1
        end
      end
    else
      each do |o|
        if o
          found_count += 1
        end
      end
    end

    (found_count > 1) ? true : false
  end

  def take_last(n)
    array = to_a

    return array if n > array.size
    array[(array.size - n)..-1]
  end

  def take_last_while
    return to_enum(:take_last_while) unless block_given?

    result = []
    reverse_each { |e| yield(e) ? result.unshift(e) : break  }
    result
  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
flash_extensions-3.0.0 lib/flash_extensions/extensions/enumerable_extension.rb
flash_extensions-1.1.0 lib/flash_extensions/extensions/enumerable_extension.rb
flash_extensions-1.0.0 lib/flash_extensions/extensions/enumerable_extension.rb