Jon Carter Jon Carter - 5 months ago 8
Ruby Question

Where's `Array#sum`?

Why does

[].sum
gives an undefined method error?

[5, 15, 10].sum
# => NoMethodError: undefined method `sum' for [5, 15, 10]:Array


Doing
ri Array#sum
returns:


Array#sum

(from gem activesupport-4.2.6) Implementation from Enumerable
------------------------------------------------------------------------------
sum(identity = 0, &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 ## <-- What?! >:(
['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)



What's going on? What am I failing to understand? Or is my installation
broken?

Answer

It mentions (from gem activesupport-4.2.6) Implementation from Enumerable.

require 'active_support'
require 'active_support/core_ext'

2.2.2 > [5, 15, 10].sum
=> 30
Comments