Creating hashes of hashes in Ruby allows for convenient two (or more) dimensional lookups. However, when inserting one must always check if the first index already exists in the hash. For example:
h = Hash.new
h['x'] = Hash.new if not h.key?('x')
h['x']['y'] = value_to_insert
It would be preferable to do the following where the new Hash is created automatically:
h = Hash.new
h['x']['y'] = value_to_insert
Similarly, when looking up a value where the first index doesn't already exist, it would be preferable if nil is returned rather than receiving an undefined method for '[]' error.
looked_up_value = h['w']['z']
One could create a Hash wrapper class that has this behavior, but is there an existing a Ruby idiom for accomplishing this task?
You can pass the Hash.new
function a block that is executed to yield a default value in case the queried value doesn't exist yet:
h = Hash.new { |h, k| h[k] = Hash.new }
Of course, this can be done recursively. There's an article explaining the details.
For the sake of completeness, here's the solution from the article for arbitrary depth hashes:
hash = Hash.new(&(p = lambda{|h, k| h[k] = Hash.new(&p)}))
The person to originally come up with this solution is Kent Sibilev.