Why does [].sum
gives an undefined method error?
[5, 15, 10].sum
# => NoMethodError: undefined method `sum' for [5, 15, 10]:Array
Doing ri Array#sum
returns:
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?
sum
isn't predefined for eitherArray
s orEnumerable
s. It may be added by a library/framework such as ActiveSupport. Otherwise, you can useinject
to calculate a sum. – Jonathan Lonowski Jun 5 '16 at 23:23