Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash default value is a hash with same default value

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] #=> {}
like image 708
Markus Avatar asked Mar 09 '26 09:03

Markus


1 Answers

Sort of mind bending, but you can pass the hash's default_proc to the inner hash:

hash = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }

hash[:foo] #=> {}
hash[:foo][:bar] #=> {}
hash[:foo][:bar][:baz] #=> {}

hash #=> {:foo=>{:bar=>{:baz=>{}}}}
like image 119
Stefan Avatar answered Mar 11 '26 01:03

Stefan