Here are my solutions to Quiz 126. Because it was the one that
popped into my mind when I read the quiz description, the first is
the one that I think I'd produce if challenged during a job interview.
<code>
# Simple, obvious (to me) way to do it.
(1..100).each do |n|
case
when n % 15 == 0 : puts 'FizzBuzz'
when n % 5 == 0 : puts 'Buzz'
when n % 3 == 0 : puts 'Fizz'
else puts n
end
end
# Not quite so obvious, but a little DRYer:
(1..100).each do |n|
puts case
when n % 15 == 0 : 'FizzBuzz'
when n % 5 == 0 : 'Buzz'
when n % 3 == 0 : 'Fizz'
else n
end
end
# Of course, could do it with if-elsif-else ...
(1..100).each do |n|
puts(
if n % 15 == 0
'FizzBuzz'
elsif n % 5 == 0
'Buzz'
elsif n % 3 == 0
'Fizz'
else n
end
)
end
# ... or even with the ternary operator.
(1..100).each do |n|
puts(
n % 15 == 0 ? 'FizzBuzz' :
n % 5 == 0 ? 'Buzz' :
n % 3 == 0 ? 'Fizz' : n
)
end
</code>
Regards, Morton