Jon Carter Jon Carter - 4 months ago 5x
Ruby Question

Where's my `Array#sum`?

I am curious about why

works as expected (returning
), but
gives me an undefined method error. Either my installation is
bad in some strange and subtle way because my experience seems to conflict with
the documentation, or there's something I'm failing to grasp (perhaps far more
likely. :) ). However, I'm not sure how to determine which it is. I fear I've
sacrificed brevity in pursuit of clarity in my attempt to describe this, and if
there's a better place to ask or a better way to ask, I'm happy to do so, and
delete this question. But this is really bugging me (My comments marked with

Array is supposed to include Enumerable, according to common sense, my prior
understanding, and the answers to this

So why does
give me an undefined method error? My attempt to
illustrate the situation follows:

## Let's fire up pry to take a look..

jon@boswell:~/bin/ruby➤ pry
[1] pry(main)> [5, 15, 10].sum
NoMethodError: undefined method `sum' for [5, 15, 10]:Array
from (pry):1:in `__pry__'

## I thought that was going to work. Let's check the docs..

[2] pry(main)> ri 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( { |i| i.amount } # =>

[3] pry(main)>

# It looks like it should work. But heck, the first non-block example they
# give is failing for me..

[3] pry(main)> [5, 15, 10].max => 15

# Okay, max() exists, and according to the docs (omitted for brevity), it's
# also provided by Enumerable.

So, what's going on? What am I failing to understand? Or is my installation
broken in some strange way?

This is long enough, so I'll close with some (perhaps) relevant info:

[4] pry(main)> exit
jon@boswell:~/bin/ruby➤ pry --version Pry version
0.10.3 on Ruby 2.3.0
jon@boswell:~/bin/ruby➤ ruby --version ruby 2.3.0p0
(2015-12-25 revision 53290) [x86_64-linux]
jon@boswell:~/bin/ruby➤ rvm --version
rvm 1.27.0 (latest) by Wayne E. Seguin <>, Michal Papis < []


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