-
-
Save McTano/7297d2509a74f9bdf4089ebbcd37d1d2 to your computer and use it in GitHub Desktop.
This file contains 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
=begin | |
The normal way: | |
def fizzbuzz(first, last) | |
first.upto(last) do |i| | |
if dividesby?(i,3) && dividesby?(i,5) | |
puts "FizzBuzz" | |
elsif dividesby?(i,3) | |
puts "Fizz" | |
elsif dividesby?(i,5) | |
puts "Buzz" | |
else | |
puts i | |
end | |
end | |
end | |
# fizzbuzz(1, 100) | |
# Or we can do it like this: | |
=end | |
def divides_by?(dividend, divisor) | |
dividend % divisor == 0 | |
end | |
def fizzbuzz(first=1, last=100, fizz_value=3, fizz_string="Fizz", buzz_value=5, buzz_string="Buzz") | |
# I used #map so that we can save the transformed array in a variable if we want. | |
(first..last).map do |x| | |
fizz = fizz_string if divides_by?(x, fizz_value) | |
buzz = buzz_string if divides_by?(x, buzz_value) | |
# (recall that, in Ruby, nil is falsey and strings are truthy) | |
(fizz || buzz) ? [fizz, buzz].join : x | |
end | |
end | |
# I took the puts out of the method so printing all those lines is intentional, not a side effect. | |
puts fizzbuzz | |
# fizzbuzz(12, 60, 4, "Vladimir ", 6, "Putin") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment