RubyQuiz: FizzBuzz
Ruby Quiz is a weekly quiz on Ruby that is used to flex your Ruby muscles, or in my case prove how completely ignorant I am on the subject entirely
The FizzBuzz quiz was one that I was actually able to accomplish in a relatively short amount of time. Unfortunately, my original solution was not very elegant at all. I used a “for next” loop with some conditional statements to achieve the desired results. Below is a copy of my original code:
for i in (1..100)
str = ""
if (i % 3) == 0
str = "Fizz"
if (i%5) ==0
str <<"Buzz"
end
elsif (i % 5) == 0
str = "Buzz"
else
str = i.to_s
end
puts str.to_s
end
While this solution was not incorrect, it was not very elegant. After doing some research I came across this article that led me to a much more elegant solution:
(1..100).each do |i|
fb = []
fb << "Fizz" if (i%3)==0
fb << "Buzz" if (i%5)==0
fb << i if (i%3)!=0 and (i%5)!=0
puts fb
end
