FizzBuzzコンバーター

最近FizzBuzz記事が多いですね。
ということで、私も乗っかってネタを一つ

ruby
# coding: UTF-8

class Converter
  
  def initialize
    @specs = []
  end
  
  def specs( value , &cond )
    @specs << lambda { |e| cond[e] ? value : nil }
  end
  
  def to_proc
    lambda { |e| 
      conved = @specs.map{ |spec| spec[e] }.join
      conved.empty? ? e : conved
    }
  end

end

if __FILE__ == $0

  ARGV[0] or raise "Requires an integer argument."
  max = ARGV[0].to_i
  
  fizzbuzz  = Converter.new

  fizzbuzz.specs( "Fizz" ){ |n| n % 3 == 0 }
  fizzbuzz.specs( "Buzz" ){ |n| n % 5 == 0 }

  puts 1.upto(max).map(&fizzbuzz)

end

追記:タイトルと関係ないけど、FizzBuzzメソッドチェイン

ruby
puts 1.upto(100).with_object(nil)
                .map { |n, o| ( o ||= [] ) << :Fizz if n % 3 == 0; [n, o] }
                .map { |n, o| ( o ||= [] ) << :Buzz if n % 5 == 0; [n, o] }
                .map { |n, o| ( o || [n] ) * "" }