Last active
December 14, 2022 09:29
-
-
Save gangelo/ef9857f58330f3ff0ae1316d1d1eee06 to your computer and use it in GitHub Desktop.
fizz buzz
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
# Fizz buzz | |
# Range 1 -> 100 (inclusive) | |
# If divisible by 3, output fizz | |
# If divisible by 5, output buzz | |
# If divisible by 3 and 5, output fizzbuzz | |
FIZZ = 'fizz'.freeze | |
BUZZ = 'buzz'.freeze | |
FIZZBUZZ = (FIZZ + BUZZ).freeze | |
def divisible_by?(dividend, *divisor) | |
return false if divisor.nil? || divisor.count == 0 | |
divisor.all? { |divisor| dividend % divisor == 0 } | |
end | |
(1..100).each do |dividend| | |
puts case | |
when divisible_by?(dividend, 3, 5) | |
FIZZBUZZ | |
when divisible_by?(dividend, 3) | |
FIZZ | |
when divisible_by?(dividend, 5) | |
BUZZ | |
else | |
dividend | |
end | |
end |
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
# Fizz buzz | |
# Range 1 -> 100 (inclusive) | |
# If divisible by 3, output fizz | |
# If divisible by 5, output buzz | |
# If divisible by 3 and 5, output fizzbuzz | |
def multiple_of_3_or_5?(number) | |
multiple_of_3?(number) && multiple_of_5?(number) | |
end | |
def multiple_of_3?(number) | |
number % 3 == 0 | |
end | |
def multiple_of_5?(number) | |
number % 5 == 0 | |
end | |
def word_for(number) | |
if multiple_of_3_or_5?(number) | |
'FizzBuzz' | |
elsif multiple_of_3?(number) | |
'Fizz' | |
elsif multiple_of_5?(number) | |
'Buzz' | |
else | |
number | |
end | |
end | |
(1..100).each_with_index do |number, index| | |
puts "#{(index + 1).to_s.rjust(3, ' ')}: #{word_for(number)}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment