18/19 example? Why sum = 0 and sum +=n?



No problem with my code but I’m confused by this example:

numbers = [5, 2, 8]
sum = 0
numbers.each do |n|
sum += n
puts sum

“The example above is just a reminder about syntax. We calculate the sum of a list of numbers.”

What is the purpose of sum = 0?

I assume that sum += n is adding all the numbers together to give us the final sum, but what does sum = 0 do?

Thank you!!!


In order to accumulate a variable using += we need to initialize the starting value. Since we want to sum up an array of numbers, we start from 0

sum = 0    # initialize the total

Now when we accumulate to the variable, we will have the correct running sum.

sum += 5
sum += 2
sum += 8

puts sum    # =>  15


thank you! that was incredibly helpful


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.