Skip to content

Instantly share code, notes, and snippets.

@skateinmars
Created August 13, 2014 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skateinmars/73162a39de019a1c44d3 to your computer and use it in GitHub Desktop.
Save skateinmars/73162a39de019a1c44d3 to your computer and use it in GitHub Desktop.
Toying with FizzBuzz
NUMS = 1..100
DISPLAYERS = NUMS.inject({}) {|acc, i| acc[i] = []; acc }
DISPLAYERS[101] = [lambda { |i| raise("finished") }]
NUMS.select {|i| i % 3 == 0 }.each {|i| DISPLAYERS[i] << lambda { |i| "Fizz" } }
NUMS.select {|i| i % 5 == 0 }.each {|i| DISPLAYERS[i] << lambda { |i| "Buzz" } }
NUMS.select {|i| (i % 3 != 0 && i % 5 != 0) }.each {|i| DISPLAYERS[i] << lambda { |i| i.to_s } }
def genfizzbuzz(num, texts = [])
text = DISPLAYERS[num].inject("") {|txt, displayer| txt + displayer.call(num) }
texts << text
genfizzbuzz(num + 1, texts)
end
accumulated_texts = []
begin
genfizzbuzz(NUMS.first, accumulated_texts)
rescue
end
puts accumulated_texts.join("\n")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment