instance method sum

Ruby on Rails 7.0.10

Since v2.2.3 Last seen in v7.0.10

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10

Signature

sum(identity = nil, &block)

Calculates a sum from the elements.

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)

Parameters

identity opt = nil
block block
Source
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 74
  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

Defined in activesupport/lib/active_support/core_ext/enumerable.rb line 74 · View on GitHub · Improve this page · Find usages on GitHub

Defined in Enumerable

Type at least 2 characters to search.

↑↓ navigate · open · esc close