Module: Enumerable
- Defined in:
- lib/gorillib/enumerable/sum.rb
Instance Method Summary collapse
-
#sum(identity = 0, &block) ⇒ Object
Calculates a sum from the elements.
Instance Method Details
#sum(identity = 0, &block) ⇒ Object
Calculates a sum from the elements. Examples:
payments.sum { |p| p.price * p.tax_rate } payments.sum(&:price)
The latter is a shortcut for:
payments.inject(0) { |sum, p| sum + p.price }
It can also calculate the sum without the use of a block.
[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:
[].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
22 23 24 25 26 27 28 |
# File 'lib/gorillib/enumerable/sum.rb', line 22 def sum(identity = 0, &block) if block_given? map(&block).sum(identity) else inject{|sum, element| sum + element } || identity end end |