Skip to content

Instantly share code, notes, and snippets.

@yoshikischmitz
Last active August 29, 2015 14:16
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoshikischmitz/f0a768d2e6239dc7d710 to your computer and use it in GitHub Desktop.
Save yoshikischmitz/f0a768d2e6239dc7d710 to your computer and use it in GitHub Desktop.
A highly extensible, declarative fizzbuzz with no hardcoded if statements, and no mutation.
applicators = {3 => "fizz", 5 => "buzz"}
fizzbuzz =
(1..100).map do |n|
fb = applicators.
select{|a| n % a == 0}.
values.join
[n.to_s, fb].max # "1" > "" and "fizz" > "100000" since "1" < "a"
end
puts fizzbuzz
@JoshCheek
Copy link

Cool idea. I came up with 2. Ruby really needs an Integer#divides?

(1..100).map do |n|
  [ [15, 'fizzbuzz'],
    [5,  'buzz'],
    [3,  'fizz'],
    [1,  n.to_s],
  ].find { |divisor, _| n % divisor == 0 }.last
end # => ["1", "2", "fizz", "4", "buzz", "fizz", "7", "8", "fizz", "buzz", "11", "fizz", "13", "14", "fizzbuzz", "16", "17", "fizz", "19", "buzz", "fizz", "22", "23", "fizz", "buzz", "26", "fizz", "28", "29", "fizzbuzz", "31", "32", "fizz", "34", "buzz", "fizz", "37", "38", "fizz", "buzz", "41", "fizz", "43", "44", "fizzbuzz", "46", "47", "fizz", "49", "buzz", "fizz", "52", "53", "fizz", "buzz", "5...

(1..100).map do |n|
  { [true,  true]  => 'fizzbuzz',
    [true,  false] => 'fizz',
    [false, true]  => 'buzz',
    [false, false] => n.to_s,
  }.fetch [n%3==0, n%5==0]
end # => ["1", "2", "fizz", "4", "buzz", "fizz", "7", "8", "fizz", "buzz", "11", "fizz", "13", "14", "fizzbuzz", "16", "17", "fizz", "19", "buzz", "fizz", "22", "23", "fizz", "buzz", "26", "fizz", "28", "29", "fizzbuzz", "31", "32", "fizz", "34", "buzz", "fizz", "37", "38", "fizz", "buzz", "41", "fizz", "43", "44", "fizzbuzz", "46", "47", "fizz", "49", "buzz", "fizz", "52", "53", "fizz", "buzz", "5...

@pmarreck
Copy link

pmarreck commented Mar 1, 2015

I figured out the same exact thing (description and all) about a year ago, albeit differently, using pure functions only

https://github.com/pmarreck/ruby-snippets/blob/master/functional%20fizzbuzz%20without%20conditionals.rb

@jschank
Copy link

jschank commented Mar 1, 2015

Here is my attempt at the same thing. Self is a fizzbuzz module - I have a variety of solution attempts...

def self.no_conditionals
  fizzy = [1,0,0]
  buzzy = [1,0,0,0,0]

  1.upto(100) do |i|
    fizzy.rotate!
    buzzy.rotate!
    str = i.to_s * (1 - (fizzy[0] | buzzy[0]))
    str << "Fizz" * fizzy[0]
    str << "Buzz" * buzzy[0]
    puts str
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment