Skip to content

Instantly share code, notes, and snippets.

@Jared-Prime
Created April 13, 2012 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jared-Prime/2372483 to your computer and use it in GitHub Desktop.
Save Jared-Prime/2372483 to your computer and use it in GitHub Desktop.
FizBuz - shorter & sweeter
# the classic FizzBuzz exercise, implemented with Ruby syntax
# at first, I wrote a script similar to the JavaScript exercise on Codeacademy.com
# Needless to say, the chain of if..else... statements just feels wrong.
# Below, with comments, is far superior code, modeled off http://www.rubyquiz.com/quiz126.html
# Start with an array of integers. We'll pass each integer individually to the block.
(1..100).each{ |i|
# Set an empty string as a default.
x = ""
# insert the word "fizz" into the string if the present integer is divisible by 3.
# This action ("divisible by") is performed by the modulus. When we use the modulus,
# we're just seeing if there's a remainder when dividing by some number.
# No remainder means, by definition, the integer is divisible by the number.
x += "fizz" if i%3==0
# Same thing as above, now we're just checking if the integer is divisible by 5.
x += "buzz" if i%5==0
# Lastly, use a ternery operator. If the string remains empty for the tested integer,
# return the integer.
# otherwise, return the string.
puts(x.empty? ? i : x);
}
# and we're done! Same logic as the Codeacademy.com FizzBuzz, but much sexier syntax!
# The full code, commented out so it doesn't print twice.
=begin
(1..100).each { |i|
x = ''
x += "fizz" if i%3==0
x += "buzz" if i%5==0
puts(x.empty? ? i : x);
}
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment