No Method Error when using .sum to an array in Ruby
Asked Answered
A

1

6

The below function will throw a NoMethodError when it is expected to calculate the sum of a given array.

By printing the result "p" it should return 10.

p [1,2,3,4].sum
#=> 10

Instead of getting the result of the sum, I get the error below.

undefined method `sum' for [1, 2, 3, 4]:Array (NoMethodError)
Ancillary answered 15/10, 2019 at 8:11 Comment(3)
sum was added in Ruby 2.4, you're probably running an older version.Oldenburg
You can do [1,2,3,4].inject(:+)Brister
According to which Ruby documentation? Are you 100% sure that the documentation you are reading is for your version of Ruby and not some other version?Efrem
D
9

Check what version of ruby you're using with ruby -v

If you have a version older than 2.4, you can use inject instead.

[1, 2, 3, 4].inject(0,:+)

The above is a shorthand for

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

The zero 0 is needed to handle empty arrays, which otherwise would return nil

Doran answered 15/10, 2019 at 8:23 Comment(2)
You might want to pass a default value, i.e. ary.inject(0, :+) to account for empty arrays.Oldenburg
Thank you, it was a version problem I had 2.3.7, not 2.4.Ancillary

© 2022 - 2024 — McMap. All rights reserved.