module Enumerable
def sum(identity = 0, &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 = 0, &block) if block_given? map(&block).sum(identity) else inject { |sum, element| sum + element } || identity end end