Why does this work?


#1

Hi guys just wondering why this works but
counter = 1
until counter > 10
puts counter
counter += 1
end

this one doesn't:


counter = 1
until counter > 10
counter += 1
puts counter
end

Why does the counter have to be after the puts?


#2

Well let's break it down!

The code works, but the lesson is asking you to print or "puts" "counter" 10 times. So with your first example let's see what the computer sees (the left column) then the output or "puts" (the right column)

Your first example:
1 + 1 = 2 || puts 1 (puts number BEFORE adding 1 to it.)
2 + 1 = 3 || puts 2
3 + 1 = 4 || puts 3
4 + 1 = 5 || puts 4
5 + 1 = 6 || puts 5
6 + 1 = 7 || puts 6
7 + 1 = 8 || puts 7
8 + 1 = 9 || puts 8
9 + 1 = 10 || puts 9
10 + 1 = 10 || NOTHING (Stops Here!)

Your second example:
1 + 1 = 2 || puts 2 (puts number AFTER adding 1 to it.)
2 + 1 = 3 || puts 3
3 + 1 = 4 || puts 4
4 + 1 = 5 || puts 5
5 + 1 = 6 || puts 6
6 + 1 = 7 || puts 7
7 + 1 = 8 || puts 8
8 + 1 = 9 || puts 9
9 + 1 = 10 || puts 10
10 + 1 = 11 || NOTHING (Stops Here!)

The difference is when "counter" gets added. Basically this means that the counter only puts out NINE " 9 " answers instead of ten like the other example you provided.

In order for your second example to work you need to set "counter = 0"

Hope this helps!


#3

Thanks a lot lolman ! I got it now. That was a great explanation :smile: