sum(identity = 0, &block)
Instance Public methods
Calculates a sum from the elements.
1 2 | payments.sum { |p| p.price * p.tax_rate } payments.sum(& :price ) |
The latter is a shortcut for:
1 | payments.inject( 0 ) { |sum, p| sum + p.price } |
It can also calculate the sum without the use of a block.
1 2 3 | [ 5 , 15 , 10 ].sum # => 30 [ 'foo' , 'bar' ].sum # => "foobar" [[ 1 , 2 ], [ 3 , 1 , 5 ]].sum => [ 1 , 2 , 3 , 1 , 5 ] |
The default sum of an empty list is zero. You can override this default:
1 | [].sum(Payment. new ( 0 )) { |i| i.amount } # => Payment.new(0) |
Please login to continue.