Sha256: 271c348979f82af6b1f28cbaacb5bb7f540de6dbf6e643f48322fd4dec24f0cb

Contents?: true

Size: 708 Bytes

Versions: 2

Compression:

Stored size: 708 Bytes

Contents

class Array
  # http://madeofcode.com/posts/74-ruby-core-extension-array-sum
  def sum(method = nil, &block)
    if block_given?
      raise ArgumentError, "You cannot pass a block and a method!" if method
      inject(0) { |sum, i| sum + yield(i) }
    elsif method
      inject(0) { |sum, i| sum + i.send(method) }
    else
      inject(0) { |sum, i| sum + i }
    end
  end unless method_defined?(:sum)

  def mean(method = nil, &block)
    sum(method, &block) / size.to_f
  end unless method_defined?(:mean)

  def grouped
    group_by { |x| x }
  end unless method_defined?(:grouped)

  def group_by
    hash = {}
    each { |x| hash[yield(x)] = x }
    hash
  end unless method_defined?(:group_by)
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pru-0.1.6 lib/pru/core_ext/array.rb
pru-0.1.5 lib/pru/core_ext/array.rb