instance method sum

Ruby on Rails 3.2.22.5

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 = 0, &block)

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)

Parameters

identity opt = 0
block block
Source
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 58
  def sum(identity = 0, &block)
    if block_given?
      map(&block).sum(identity)
    else
      inject(:+) || identity
    end
  end

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

Defined in Enumerable

Type at least 2 characters to search.

↑↓ navigate · open · esc close