Skip to content

Instantly share code, notes, and snippets.

@allthetime
Forked from kvirani/README.md
Last active August 29, 2015 14:06
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 allthetime/be387225ec34e5282132 to your computer and use it in GitHub Desktop.
Save allthetime/be387225ec34e5282132 to your computer and use it in GitHub Desktop.

You should be familiar with this code, but go ahead and execute it to make sure it’s working as expected.

Let’s now make our fizzbuzz more robust and flexible.

Task 1

Refactor (improve) this code by implementing a method (called fizzbuzz) that takes in the starting and ending number so that we can programmatically change which numbers our fizzbuzz starts and ends at, instead of the usual 1 and 100.

Task 2

Think about other methods that can be implemented to further refactor this code and make it more readable. Remember that readability does not necessarily mean fewer lines of code.

def fizzbuzz(first,last)
(first..last).each do |number|
print "Fizz" if number.divisible_by?(3)
print "Buzz" if number.divisible_by?(5)
if !(number.divisible_by?(3) || number.divisible_by?(5))
print number
end
puts
end
end
class Integer
def divisible_by?(x)
self % x == 0 ? true : false
end
end
#example
fizzbuzz(1,15)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment