Created
April 13, 2012 01:01
-
-
Save Jared-Prime/2372483 to your computer and use it in GitHub Desktop.
FizBuz - shorter & sweeter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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