From: Mike Stok Date: 2013-06-23T23:41:49+09:00 Subject: Re: Confusin with Hash default On 2013-06-23, at 3:33 AM, Love U Ruby wrote: > Humm.. Great catch.. Thanks for your help ; > > h = {} > h[:a] = 2 > h # => {:a=>2} > > h = Hash.new([]) > h[:a] = h[:a] << 2 > h # => {:a=>[2]} > > -- > 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 = Hash.new([]) => {} [2] pry(main)> h[:a] << 2 => [2] [3] pry(main)> h[:b] << 3 => [2, 3] [4] pry(main)> h[:a].object_id => 70203880282800 [5] pry(main)> h[:b].object_id => 70203880282800 [6] pry(main)> h.default => [2, 3] [7] pry(main)> h.keys => [] [8] pry(main)> h => {} 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 = Hash.new { |h, k| h[k] = [] } => {} [10] pry(main)> h2[:a] << 2 => [2] [11] pry(main)> h2[:b] << 3 => [3] [12] pry(main)> h2[:a].object_id => 70203901671420 [13] pry(main)> h2[:b].object_id => 70203903870340 [14] pry(main)> h2 => {:a=>[2], :b=>[3]} Hope this helps, Mike -- Mike Stok http://www.stok.ca/~mike/ The "`Stok' disclaimers" apply.