Skip to content

Instantly share code, notes, and snippets.

@masassiez
Created January 25, 2012 15:20
Show Gist options
  • Save masassiez/1676753 to your computer and use it in GitHub Desktop.
Save masassiez/1676753 to your computer and use it in GitHub Desktop.
FizzBuzzクラス
class FizzBuzz
def initialize( from = 1, to = 30 )
@from, @to = [ from, to ].minmax
block_given? ? yield( self ) : self
end
def spec( out, &cond )
( @specs ||= [] ) << lambda { |e| cond[ e ] ? out : nil }
end
def edit( &editor )
@editor = editor
end
def editor
@editor || lambda { |e| e }
end
def format( &formatter )
@formatter = formatter
end
def output( &formatter )
@formatter = formatter if formatter
result = @from.upto( @to ).map( &self )
@formatter ? result.map { |e| @formatter[ e ] } : result
end
def to_proc
lambda { |i|
outs = @specs.map { |spec| spec[ i ] }
editor[ i, outs ]
}
end
end
require "./fizzbuzz"
# Pattern 1 : (1..30)
FizzBuzz.new do |fizzbuzz|
fizzbuzz.spec( :Fizz ) { |e| e % 3 == 0 }
fizzbuzz.spec( :Buzz ) { |e| e % 5 == 0 }
fizzbuzz.edit { |i, outs|
out = outs.join
out.empty? ? i : out
}
end.output do |e|
puts e
end
# Pattern 2 : (31..69)
fizzbuzz = FizzBuzz.new(31, 69)
fizzbuzz.edit { |i, outs|
out = outs.join
out.empty? ? i : out
}
fizzbuzz.spec( :B ) { |e| e % 5 == 0 }
fizzbuzz.spec( :F ) { |e| e % 3 == 0 }
result = fizzbuzz.output
puts result * " "
# Pattern 3 : (70..105)
FizzBuzz.new(70, 105) do |fizzbuzz|
fizzbuzz.spec( :Pizz ) { |e| e % 3 == 0 }
fizzbuzz.spec( :Quzz ) { |e| e % 5 == 0 }
fizzbuzz.spec( :Razz ) { |e| e % 7 == 0 }
fizzbuzz.edit { |i, outs|
out = outs.join
out.empty? ? i : out
}
fizzbuzz.format { |e| puts e }
end.output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment