Setting a default value of a hash like this:
hash = Hash.new { |hsh, key| hsh[key] = {} }
will create (and assign) a new hash for an unknown key, but will return nil
for an unknown key of the created hash:
hash[:unkown_key] #=> {}
hash[:unkown_key][:nested_unknown] #=> nil
I could make it work for the second level like this:
hash = Hash.new do |hsh, key|
hsh[key] = Hash.new { |nest_hsh, nest_key| nest_hsh[nest_key] = {} }
end
but, it does not work at the third level:
hash[:unkown_key][:nested_unknown] #=> {}
hash[:unkown_key][:nested_unknown][:third_level] #=> nil
How can I make it work at arbitrary levels?
hash[:unkown_key][:nested_unknown][:third_level][...][:nth_level] #=> {}
You could create
method
that will do this with RecursionSort of mind bending, but you can pass the hash's
default_proc
to the inner hash: