ハッシュをネストしてカウンタを作るとき
Rubyはハッシュのネストが簡単にはできないので、メソッド定義しないと駄目っぽい。
#counterに入っているHash配下に、pathで示されたHashのネストを作成する。 #末尾のHashオブジェクトはHash.new(0)となって、カウンタに使う。 #戻り値は末尾のカウンタ用Hashオブジェクト(Hash.new(0)のもの) def make_counter(counter, path) head, *tail = path if tail.empty? counter[head] ||= Hash.new(0) else counter[head] ||= Hash.new make_counter(counter[head], tail) end end
こんな感じで使います。
counter = Hash.new cnt = make_counter(counter, %w{ a b c }) pp counter #=> {"a"=>{"b"=>{"c"=>{}}}} pp cnt[:d] #=> 0 pp cnt[:d] += 100 #=> 100 pp counter[:c] #=> nil #まだcounte[:c]は作成されていないので、普通にnilになる。