As I was working through my Harvard CS50 problem sets, I tackled FizzBuzz in C. I am currently working through my Flatiron School prework and reviewing loops and control flow in Ruby.
Ruby shares many similarities to other programming languages, but its loops are quite different, mainly in the way they are initialized. For example, in C and many other languages, a for loop would be initialized using something like:
for (int i = 1; i <=100; i++)
This means i (which was declared as an integer) would start with a value of 1 and the loop would increment by 1 as long as i had a value of less than or equal to 100. Seems simple enough.
In Ruby, the same for loop would be initialized with the following:
for i in 1..100 do
This is simpler and more powerful, but still accomplishes the same task – the value of i in the first iteration of the loop is 1 and the loop continues to increment by 1 while the value of i is less than or equal to 100. There is no need to declare a variable type in Ruby.
This brings me to FizzBuzz. Although the Ruby for loop initializes quite differently, the conditions inside the loop remain the same:
for i in 1..100 do if ((i % 5) == 0) && ((i % 3) == 0) puts "FizzBuzz" elsif (i % 5) == 0 puts "Buzz" elsif (i % 3) == 0 puts "Fizz" else puts "#{i}" end end
Output:
Of course, there are minor changes in syntax between C and Ruby: (1) else if becomes elsif , (2) printf is replaced with puts, and \n is no longer necessary, (3) curly brackets and semicolons are removed, (4) instead of return 0; the loop terminates withend , and (5) variables are referenced differently when printing – (“%d”, i) is replaced with “#{i}” .
- PM Career Story - April 28, 2022
- How to Transition into Product Management - December 26, 2017
- What I’ve Learned in My First Few Months as a Product Manager - October 14, 2015
Clarinda says
This is way more helpful than anhyitng else I’ve looked at.
Koren Leslie Cohen says
Awesome!