On 10/29/07, Lars Ticot <nicolas.rassat / free.fr> wrote: > I try to get a hash of hash to make some sort of counter (I have a set > of random pair and want to count the number of times they appear). I use > this code but even if I can access data, my hash seems empty (so each > and the others don't work): > > > h = Hash.new(Hash.new(0)) > h["a"]["b"] += 1 > h["a"]["b"] += 1 > h["a"]["c"] += 1 > p h["a"]["b"] => 2 > p h["a"]["c"] => 1 > p h.class => Hash > p h["a"].class => Hash > p h["a"]["b"].class => Fixnum > p h => {} > > > What's wrong? You're using the wrong form of Hash.new for this use case. Hash.new(default) gives you a hash which simply returns default from [key] when key doesn't exist, it leaves the hash itself alone. You need to use a block h = Hash.new {|h, k| h[k] = Hash.new(0)} h["a"]["b"] += 1 h["a"]["b"] += 1 h["a"]["c"] += 1 h["a"]["b"] # => 2 h["a"]["c"] # => 1 h.class # => Hash h # => {"a"=>{"b"=>2, "c"=>1}} -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/