sum(identity = 0, &block) public

Calculates a sum from the elements. Examples:

 payments.sum { |p| p.price * p.tax_rate }
 payments.sum(&:price)

This is instead of payments.inject { |sum, p| sum + p.price }

Also calculates sums without the use of a block:

  [5, 15, 10].sum # => 30

The default identity (sum of an empty list) is zero. However, you can override this default:

[].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)

Show source
Register or log in to add new notes.