If I do the following:
h = Hash.new(Array.new)
h['a'].push('apple')
puts h['a']
puts h
I get the following output:
apple
{}
I don't understand why puts h isn't outputing:
{"a"=>["apple"]}
Any help much appreciated...
Read this
new(obj) → new_hash
If
objis specified, this single object will be used for all default values.
Hash.new(Array.new) - by this line you have created a default array object. Which will be returned whenever you want to access a key, which not exist inside the hash.
h['a'].push('apple') - By this line, you actually adding/pushing a value to that default array object,but not adding any key to the hash. h['a'] is returning you the array you defined with Array.new, on that you are calling Array#push, that's all.Thus h['a'] is giving you the current content of that default array. puts h ofcourse will give you {}, as you didn't added the key 'a' to the hash.
See the same in action :
h = Hash.new(Array.new)
h.default # => []
h['a'].push('apple')
h.default # => ["apple"]
Now look the code again :
#adding a key
h['a'] = 'Bob'
h['a'] # => "Bob"
h # => {"a"=>"Bob"}
#again default vaule as you are trying to aceess a non-exist key
h['b'] # => ["apple"]
Worth to read Hash#[]
Element Reference— Retrieves the value object corresponding to the key object. If not found, returns the default value (see
Hash::newfor details).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With