Skip to content

Instantly share code, notes, and snippets.

@yahihi
Created August 30, 2012 03:36
Show Gist options
  • Save yahihi/3522055 to your computer and use it in GitHub Desktop.
Save yahihi/3522055 to your computer and use it in GitHub Desktop.
class BaseCounter
def initialize
@strike = 0
@ball = 0
@out = 0
end
def strike
@strike += 1
if @strike == 3
out
hitter_change
end
end
def ball
@ball += 1
if @ball == 4
hitter_change
end
end
def get_count
#output = @out.to_s + @strike.to_s + @ball.to_s
#print output
return [ @out,@strike,@ball ]
end
protected
def out
@out += 1
@out = 0 if @out == 3
hitter_change
end
def hitter_change
@strike = 0
@ball = 0
end
end
class Counter < BaseCounter
def foul
strike unless @strike == 2
end
def pitcher_fly
out
hitter_change
end
def hit
hitter_change
end
end
DIC = {
"o" => :out,
"s" => :strike,
"b" => :ball,
"f" => :foul,
"p" => :pitcher_fly,
"h" => :hit,
}
input =STDIN.gets.chomp
output = []
counter = Counter.new
for i in 0...input.size
counter.send(DIC[input[i,1]])
output[i] = counter.get_count.join
end
print input
print " > "
print output.join ","
@yahihi
Copy link
Author

yahihi commented Aug 30, 2012

@yahihi
Copy link
Author

yahihi commented Aug 30, 2012

訂正
instance.methodsでメソッドの一覧をアレイで得られることがわかったので、頭文字とメソッド名の対応ハッシュを自動で作成できるよう調整した
methodsは真偽値を引数に取り、falseを引数にとる場合は継承したメソッドを含まない
なので、クラス構成をスーパークラスのpublicにアクセスさせたいメソッド、実クラスにgetterメソッドだけ実装した
そして、スーパークラスの継承していないパブリックメソッド一覧から、頭文字をkey、シンボルをvalueとした辞書を作った
STDINの頭文字から辞書を頼りにシンボルを出し、instanceからsendで動的にメソッドを呼び出している

class Counter 
    def initialize
        @strike = 0
        @ball = 0
        @out = 0
    end

    def strike
        @strike += 1
        if @strike == 3
            out
            hitter_change
        end
    end

    def ball
        @ball += 1
        if @ball == 4
            hitter_change 
        end
    end

    def foul
        strike unless @strike == 2
    end

    def pitcher_fly
        out
        hitter_change
    end

    def hit
        hitter_change
    end

    private
    def out
        @out += 1
        @out = 0 if @out == 3
        hitter_change
    end

    def hitter_change
        @strike = 0
        @ball = 0
    end
end

class CounterAccssesser < Counter
    def get_count
        return [ @out,@strike,@ball ]
    end
end

def make_dictionary
    methods_array = Counter.public_instance_methods(false)
    dic = {}
    methods_array.each do |method|
        key = method[0,1]
        value = method.to_sym
        dic[key] = value
    end
    return dic
end

dic = make_dictionary
input =STDIN.gets.chomp
#input = "ssbbffpp"
output = []
counter = CounterAccssesser.new

for i in 0...input.size
    counter.send(dic[input[i,1]])
    output[i] = counter.get_count.join
end

print input
print " > "
print output.join ","

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment