The default value for the hash does not work as you expect. When you say h[k] , the process will look like this:
- If we have key
k , return its value. - If we have a default value for Hash, return that default value.
- If we have a block to provide default values, execute the block and return its return value.
Note that (2) and (3) say nothing about inserting k into the hash. By default, the default turns h[k] into this:
h.has_key?(k) ? h[k] : the_default_value
Thus, simply accessing a non-existent key and getting the default value back will not add the missing key to the hash.
In addition, anything:
Hash.new([ ... ])
it is almost always a mistake, because for all default values you will use exactly the same default array or Hash. For example, if you do this:
h = Hash.new(['a']) h[:k].push('b')
Then h[:i] , h[:j] , ... all will return ['a', 'b'] and this is rarely what you want.
I think you are looking for the default block form :
h = Hash.new { |h, k| h[k] = [ 'alright' ] }
This will do two things:
- Access to a nonexistent key will add this key to the Hash, and it will have the provided array as its value.
- All default values will be different objects, so changing them will not change the rest.
mu is too short
source share