2

这是进行经典FizzBu​​zz 练习的一种相当非正统的方法,但这只是为了说明问题(嘿,如果你想将 fizzbuzz 提高到十亿,它可能会很快)。

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

如何概括此代码以接受像 {3 => 'Fizz', 5 => 'Buzz', 7 => 'Boozz'} 这样的哈希?

4

1 回答 1

3

创建一组 Fizzers、Buzzers 和 Boozzers。next然后在该数组中每个 fooer的循环调用中,然后将结果与inject

# The sort is needed so it prints fizzbuzz, not buzzfizz
# (hashes being unordered and all)
fooers = the_hash.sort_by {|k,v| k}.map do |k,v|
  ( Array.new(k - 1, '') << v ).cycle
end

(1..100).each do |number|
  fizzbuzz = fooers.map(&:next).inject(:+)
  puts ( fizzbuzz.empty? ? number : fizzbuzz )
end
于 2010-11-12T00:19:51.477 回答