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 # we check `first(1) == []` to check if we have an # empty Enumerable; checking `empty?` would return # true for `[nil]`, which we want to deprecate to # keep consistent with Ruby elsif first.is_a?(Numeric) || first(1) == [] || first.respond_to?(:coerce) identity ||= 0 _original_sum_with_required_identity(identity, &block) else 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 inject(:+) || 0 end end