Fizz Buzz

As seen on a thread on Hacker News about Fizz Buzz and “interesting” functional ways to solve it.  Realized that there are many ways to boil the ocean, but this feels like a nice compromise between data/program separation and language.

Note this is using a “Bazz” variant of the FizzBuzz problem where Bazz is printed every 7 numbers.

    cases = [(3, "Fizz"), (5, "Buzz"), (7, "Bazz")]

    for i in range(110):
        pr = ''.join([s * (i % m == 0) for m, s in cases])
        print pr or i

Also read...

  • http://twitter.com/stevewilhelm Steve Wilhelm

    Any way to make this Ruby implementation cleaner?

    (1..109).each do |i|
    pr = cases.inject(“”) {|val, el|  val + el[1] * ((i % el[0] == 0) ? 1 : 0) }
    puts (!pr.empty?) ? pr : i
    end

  • http://skitoy.com koblas

    No quick ideas – though why:   puts (!pr.empty?) ? pr : i — rather than puts pr.empty? ? i : pr

    Oh – wait, that’s part of what drives me crazy about ruby… the syntax is a bit wonky.