Accumulators in Ruby
Today I thought I’d try a spot of Rubber-ducking. No, I’m not in the bath. Rubber ducking is the process of explaining something in the simplest possible terms in order to make sure you understand it fully. I am going to explain a problem that I got stuck on during the pre-course for Makers. Many thanks to Igor and Muzzi for helping me out with this one.
So the question was how to add up numbers in a range eg. 1+2+3+4+5 and puts out the total. The curriculum content covered using the while statement and a conditional argument to create a loop. It also explained that you had to define a variable outside the loop in order to prevent it from re-setting every time the loop ran.
This is what I started with, and it will output every number in the range one after another until number was equal to 34.
What it does is re-define number as itself plus one so on the first iteration of the loop number = 0 +1 (1) and on the second number = 1+1 (2) and so on. What I wanted to to was add each iteration of number to the previous iteration. Sounds simple, no?
The first thing I thought was since I needed to add the first iteration of number to the second iteration I would try adding number to number inside the loop. All this did was to double the output, so instead of getting 1, 2, 3, 4, I got 2, 4, 6, 8.
Why was my thinking wrong? I didn’t actually want to add number to itself, I wanted to add each iteration of number to itself. This is where I got stuck, I could not work out for the life of me how to add different iterations to each other. So after much head-scratching and a message on slack, my fellow Makers Igor and Muzzi helped me to find the answer.
Get Anders Persson’s stories in your inbox
Join Medium for free to get updates from this writer.
I already had the solution in my code, I just hadn’t worked out that I needed to apply it to provide a running total. What I needed was an extra variable (defined outside the loop) to add number to that would give me a running total of the sum of each iteration.
The example above still gave me a series of numbers but each iteration was the sum of the previous iterations so I knew I was almost there. The final piece of the puzzle was to move the puts statement out of the loop which would give me the total sum.
What did I learn?
Firstly, that if you are stuck you should always ask for help. Asking for help means you get to the solution quicker and understand it fully.
Secondly, that when adding iterations both the number and the running total have to be defined outside the loop for them to remember previous iterations.
Thirdly, that you can replace number = number + 1 with number += 1.
And finally, a puts statement inside the loop will puts out every iteration whereas a puts statement outside the loop will just print the final iteration.
So there we go, a simple problem I couldn’t get my head round but now fully rubber-ducked for your enjoyment.






