This is a rather unorthodox way to do the classic FizzBuzz exercise, but it’s just to illustrate the problem (and hey, it might be fast if you want to fizzbuzz to a billion).
fizzer = ( Array.new( 2, '' ) << 'Fizz' ).cycle
buzzer = ( Array.new( 4, '' ) << 'Buzz' ).cycle
(1..100).each do |number|
fizzbuzz = fizzer.next + buzzer.next # this line is giving me problems.
puts ( fizzbuzz.empty? ? number : fizzbuzz )
end
How to generalize this code to accept a hash like {3 => ‘Fizz’, 5 => ‘Buzz’, 7 => ‘Boozz’} ?
Create an array of Fizzers, Buzzers, and Boozzers. Then in the loop call
nexton each fooer in that array and then sum the results withinject: