关于ruby:哪里是’Array#sum`?

Where's `Array#sum`?

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

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

执行ri Array#sum返回:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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)

发生什么事?我为什么不明白?或者是我的安装坏了吗?


它提到(来自gem activesupport-4.2.6)可枚举的实现。

1
2
3
4
5
require 'active_support'
require 'active_support/core_ext'

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


在大多数答案中,上面已经说明了sum不是数组的一个实例方法。

您可以使用object.methods查看对象上的所有可用方法。示例[1,2,3].方法。也可以参考http://apidock.com/ruby/array

1
[1,2,3].inject(0) {|sum,x| sum + x }