Skip to content

Instantly share code, notes, and snippets.

@plagelao
Created August 14, 2011 10:39
Show Gist options
  • Save plagelao/1144782 to your computer and use it in GitHub Desktop.
Save plagelao/1144782 to your computer and use it in GitHub Desktop.
fizzbuzz FP style
def fizzbuzz_strings
fizz = ->(number) { 'fizz' }
buzz = ->(number) { 'buzz' }
default = ->(number) { number.to_s }
[fizz, buzz, default]
end
def fizzbuzz_rules
multiple_of_3 = ->(number) { number % 3 == 0 }
multiple_of_5 = ->(number) { number % 5 == 0 }
criterias = [multiple_of_3, multiple_of_5]
default = ->(number) { not criterias.any?{|c| c.(number)} }
[multiple_of_3, multiple_of_5, default]
end
def fizzbuzz_strategy
fizzbuzz_rules.zip(fizzbuzz_strings)
end
def strings_for(number)
fizzbuzz_strategy.select{|criteria_for, _| criteria_for.(number)}.
map{|_, string_for| string_for.(number)}
end
def fizzbuzz(number)
strings_for(number).join
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment