When Ashley, one of our amazing instructors, asked students to try FizzBuzz, I had a ear to ear grin o my face. However, my smiley face became suddenly quizzical as soon as she mentioned doing it in Ruby. It caught me unprepared because I was not 100% confident in using loops in this language. At least, I wasn’t sure which one to use as there are a bazzilion ways to code them, methods such as “.times”, “.each” are only the tip of the iceberg.
The state is the i = 1; part; it declares a variable to use for the counting, and sets its start value–here it has the start value of 1. The variable exists only within the loop (down through the ” } ” of the body.
Typically, the test is a boolean expression such as ” i < 101″, showing what should be true for the loop to continue.
Finally, the increment code executes and then the program loops back to the state. The increment advances the state of things in preparation for the next iteration. The “i++” means incrementing the variable “i” by one. It is the same thing as i = i +1.
So we have when it should start i = 1, when it should stop, when i < 101, and by how much it is adding in each iteration i+1. In my opinion this is explicit and clear.
In Ruby, I learned today, that the state, condition and increment is hidden in the object method. In the end I managed to create my FizzBuzz in Ruby. Check out the code below.