module Enumerable
def sum(identity = nil, &block)
The default sum of an empty list is zero. You can override this default:
[[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
['foo', 'bar'].sum # => "foobar"
[5, 15, 10].sum # => 30
It can also calculate the sum without the use of a block.
payments.inject(0) { |sum, p| sum + p.price }
The latter is a shortcut for:
payments.sum(&:price)
payments.sum { |p| p.price * p.tax_rate }
Calculates a sum from the elements.
def sum(identity = nil, &block) if block_given? map(&block).sum(identity) else sum = identity ? inject(identity, :+) : inject(:+) sum || identity || 0 end end