Jon Carter - 1 year ago 50

Ruby Question

Why does

`[].sum`

`[5, 15, 10].sum`

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

Doing

`ri Array#sum`

`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 Source

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
```