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

Viewed 620

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)
1 Answers

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

Related