Fun with FizzBuzz

I decided to make FizzBuzz into something that reads (nominally) like English … because I’m easily amused.

fizz_or_buzz = (1..100)

fizzbuzz = fizz_or_buzz.map do |i|
  not_fizzy = (i % 3 != 0)
  not_buzzy = (i % 5 != 0)
  no_fizz_no_buzz = i.to_s
  when_fizzy = (i % 3)
  when_buzzy = (i % 5)

  if not_fizzy && not_buzzy
    fizziness = [no_fizz_no_buzz]
  else
    fizziness = [ ["Fizz"][when_fizzy], ["Buzz"][when_buzzy] ]
  end

  fizziness.compact.join
end

puts fizzbuzz

There’s a fun little trick in the else clause, taking advantage of ruby’s handling of nil elements in a 2 element array. It’s a *really bad* coding practice, but fun to play with. You can see an explanation of the nil handling here.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.