Array#sum在哪里?

Jon*_*ter 3 ruby

为什么会[].sum给出未定义的方法错误?

[5, 15, 10].sum 
# => NoMethodError: undefined method `sum' for [5, 15, 10]:Array 
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

这是怎么回事?我不明白什么?还是我的安装坏了?

Nab*_*eel 5

它提到了(来自gem activesupport-4.2.6)来自Enumerable的实现

require 'active_support'
require 'active_support/core_ext'

2.2.2 > [5, 15, 10].sum
=> 30
Run Code Online (Sandbox Code Playgroud)