On Thu, Nov 17, 2011 at 6:45 PM, Florent G. [email protected] wrote:
hash[:b] << 2
puts hash[:b]
=> returns [2]
puts hash.keys
=> returns [:a], not [:a, :b] ?
hash[:b] is set to [2] but I don’t understand why hash.keys does not
include :b.
The reason is that the Hash constructor you are using uses the object
you pass, in your case, Array.new, to return when you access a
non-existing key. But, it doesn’t assign the array to the key. You
have to do it yourself. One way is to use the default proc:
h = Hash.new {|hash, k| hash[k] = Array.new}
This will create a new array and assign it to a key, whenever you
access a non-existing key: