On Mon, Dec 5, 2011 at 5:28 PM, Chad Perrin <code / apotheon.net> wrote:
> Ruby (1.9.3p0 to be precise, installed with RVM) is not behaving as I
> expected.
>
> > foo = Hash.new( Hash.new )
> > {}
> > foo[3][2] = true
> > true
> > foo
> > {}
> > foo[3]
> > {2=>true}
> > foo[2]
> > {2=>true}
> > foo
> > {}
> >

Using that Hash constructor, what you pass is the default value for a
missing key. What this means is that the hash will return that object
to any call in which the key is not found. *But* it won't assign that
default object to the key. You have to do that yourself. The other
effect you are seeing is that the default object is returned for all
missing keys, hence the {2 => true} for foo[2].

>
> What I would expect would be something more like this:
>
> > foo = Hash.new( Hash.new )
> > {}
> > foo[3][2] = true
> > true
> > foo
> > {3=>{2=>true}}
> > foo[3]
> > {2=>true}
> > foo[2]
> > {}
> > foo
> > {3=>{2=>true}}
> >
>
> Where and why do my assumptions fail me?

If you want that behaviour you have to use the default proc, in which
you define how you handle a missing key:

foo = Hash.new {|h,k| h[k] = {}}
foo[3][2] = true
foo => {3 => {2 => true}}
foo[2] => nil

Hope this helps,

Jesus.