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 identity _original_sum_with_required_identity(identity, &block) elsif block_given? map(&block).sum else first = true reduce(nil) do |sum, value| if first first = false unless value.is_a?(Numeric) || value.respond_to?(:coerce) ActiveSupport::Deprecation.warn(<<-MSG.squish) Rails 7.0 has deprecated Enumerable.sum in favor of Ruby's native implementation available since 2.4. Sum of non-numeric elements requires an initial argument. MSG end value else sum + value end end || 0 end end