Tuesday, November 13, 2007

Rails: Enumerable#sum

Documentation
Calculates a sum from the elements. Examples:

payments.sum { |p| p.price * p.tax_rate }
payments.sum(&:price)

This is instead of payments.inject { |sum, p| sum + p.price }

Also calculates sums without the use of a block:

[5, 15, 10].sum # => 30

The default identity (sum of an empty list) is zero. However, you can override this default:

[].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
Usage
The Enumerable#sum method does exactly what you would expect: Sum the elements of the array.

Test

require 'rubygems'
require 'active_support'
require 'test/unit'
require 'dust'

unit_tests do
test "sum the numbers from the array" do
grades = [50, 55, 67, 62, 71, 89, 84, 85, 99]
assert_equal 662, grades.sum
end
end

2 comments:

  1. still useful after all these years

    ReplyDelete
  2. It is worth noting that when you pass a block to sum() it will evaluate slower than inject. Check out this article to find out why.
    http://afewgoodlines.com/post/911224306/ruby-enumerable-sum-implementation-and-performance

    ReplyDelete

Note: Only a member of this blog may post a comment.