On 2013-06-23, at 3:33 AM, Love U Ruby <lists / ruby-forum.com> wrote:

> Humm.. Great catch.. Thanks for your help ;
>=20
> h =3D {}
> h[:a] =3D 2
> h # =3D> {:a=3D>2}
>=20
> h =3D Hash.new([])
> h[:a] =3D h[:a] << 2
> h # =3D> {:a=3D>[2]}
>=20
> --=20
> Posted via http://www.ruby-forum.com/.

Watch out using Hash.new([]) - you have to be aware of what it does.  It =
sets the hash's default object, and there is only one of them per hash, =
and you might not see the expected list of keys because you are updating =
the Hash's default object:

ratdog:tmp mike$ pry
[1] pry(main)> h =3D Hash.new([])
=3D> {}
[2] pry(main)> h[:a] << 2
=3D> [2]
[3] pry(main)> h[:b] << 3
=3D> [2, 3]
[4] pry(main)> h[:a].object_id
=3D> 70203880282800
[5] pry(main)> h[:b].object_id
=3D> 70203880282800
[6] pry(main)> h.default
=3D> [2, 3]
[7] pry(main)> h.keys
=3D> []
[8] pry(main)> h
=3D> {}

If you specify a block then you can get a new object for each time you =
need a default, and get the kind of behaviour most people expect:

[9] pry(main)> h2 =3D Hash.new { |h, k| h[k] =3D [] }
=3D> {}
[10] pry(main)> h2[:a] << 2
=3D> [2]
[11] pry(main)> h2[:b] << 3
=3D> [3]
[12] pry(main)> h2[:a].object_id
=3D> 70203901671420
[13] pry(main)> h2[:b].object_id
=3D> 70203903870340
[14] pry(main)> h2
=3D> {:a=3D>[2], :b=3D>[3]}

Hope this helps,

Mike

--=20

Mike Stok <mike / stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.