如何推进多个枚举器,或者“但是 FizzBuzzBoozz 呢?”
这是进行经典 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 =>; 的哈希值'嘶嘶', 5 => '嗡嗡', 7 => ‘嘘’}?
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'} ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建 Fizzers、Buzzers 和 Boozzer 数组。然后在循环中对该数组中的每个 fooer 调用
next
,然后使用inject
将结果相加:Create an array of Fizzers, Buzzers, and Boozzers. Then in the loop call
next
on each fooer in that array and then sum the results withinject
: