Ruby 1.9 で FizzBuzz

Ruby 1.9.1 もリリースされたことだし,新機能(Fiber と Array#cycle)を使ってFizzBuzz を書いてみたよ。d:id:takatoh:20070509:fizzbuzzRuby版。

cf. Ruby 1.9.1 の歩き方 - るびま 0025号

 # -*- encoding: utf-8 -*-
 
 fizzbuzz = Fiber.new do
   fizz = ["", "", "Fizz"].cycle
   buzz = ["", "", "", "", "Buzz"].cycle
   n = 1
   while
     s = fizz.next + buzz.next
     Fiber.yield(s == "" ? n.to_s : s)
     n += 1
   end
 end
 
 
 100.times{ puts fizzbuzz.resume }

実行結果は省略。

追記:

Fiber ってスレッドに似た云々とかいうより,途中で評価を中断出来る(&途中の値を返せる)クロージャだと考えた方がわかりやすいんじゃないかと思った。