Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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