This question already has an answer here:
Ruby lets you define default values for hashes:
h=Hash.new(['alright'])
h['meh'] # => ["alright"]
Assignment of a value shows up when displaying the hash, but a modified default does not. Where's 'bad'
?
h['good']=['fine','dandy']
h['bad'].push('unhappy')
h # => {"good"=>["fine", "dandy"]}
'bad'
shows up if we explicitly ask.
h['bad'] # => ["alright", "unhappy"]
Why does the modified default value not show up when displaying the hash?
What's happened is that you have modified the default value of the hash, by
push
ing 'unhappy' ontoh['bad']
. What you haven't done is actually added 'bad' to the hash, which is why it doesn't show up when you inspecth
.After all the code you supplied, I tried this:
Which certainly suggests to me that the default value has been changed. In answer to your question 'Why does the modified default not show up when displaying the hash?', you would have to add an element to it, rather than just accessing it:
Hash's default value doesn't work like you're expecting it to. When you say
h[k]
, the process goes like this:k
key, return its value.Note that (2) and (3) say nothing at all about inserting
k
into the Hash. The default value essentially turnsh[k]
into this:So simply accessing a non-existant key and getting the default value back won't add the missing key to the Hash.
Furthermore, anything of the form:
is almost always a mistake as you'll be sharing exactly the same default Array or Hash for for all default values. For example, if you do this:
Then
h[:i]
,h[:j]
, ... will all return['a', 'b']
and that's rarely what you want.I think you're looking for the block form of the default value:
That will do two things: