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?
Hash’s default value doesn’t work like you’re expecting it to. When you say
h[k], the process goes like this:kkey, return its value.Note that (2) and (3) say nothing at all about inserting
kinto 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: