哪里是'数组#sum`?

时间:2016-06-05 23:16:59

标签: ruby

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

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

执行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)

发生了什么?我什么不明白?或者是我的装置 破?

2 个答案:

答案 0 :(得分:5)

它提到(来自gem activesupport-4.2.6 Enumerable 的实施。

require 'active_support'
require 'active_support/core_ext'

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

答案 1 :(得分:1)

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

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

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