instance method
sum
Ruby on Rails 5.2.8.1
Since v2.2.3 Last seen in v7.0.10Signature
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
-
identityopt = nil -
blockblock
Source
# File activesupport/lib/active_support/core_ext/enumerable.rb, line 38
def sum(identity = nil, &block)
if identity
_original_sum_with_required_identity(identity, &block)
elsif block_given?
map(&block).sum(identity)
else
inject(:+) || 0
end
end
Defined in activesupport/lib/active_support/core_ext/enumerable.rb line 38
· View on GitHub
· Improve this page
· Find usages on GitHub
Defined in Enumerable