I have executed the following in irb:
irb(main):068:0* map = Hash.new(Array.new)
=> {}
irb(main):069:0> map["a"]
=> []
irb(main):070:0> map["a"].push("hello")
=> ["hello"]
irb(main):071:0> map["a"].push(1)
=> ["hello", 1]
irb(main):072:0> map.has_key?("a")
=> false
irb(main):073:0> map.keys
=> []
irb(main):074:0>
Why is it that once i have added key "a"
to the hash it is not appearing in the result of Hash#keys
?
Thanks
The Problem
By calling
you alter the Hash's default object. In fact, after that, every possible key will deliver "hello", but the key isn't really initialized. The hash will only know its default object, but you didn't tell it to "initialize" the key.
What you might want to do is specifically initialize the key:
But this isn't really what you want.
Solution:
This default behavior can be achieved by using the following method to initialize the hash:
For example:
(I'm no Ruby expert, so if there are some suggestions please add a comment)