I am looking for a concise way to set the value into a hash deep given a list of key accessors.
path = [:mountain, :river, :tree]
hash = {}
deep_nest(hash, path, 23)
=> { mountain: { river: { tree: 23 } } }
I get it working with the following code
deep = path.inject(hash) do |hash, field|
if hash.key?(field)
hash[field]
else
hash[field] = {}
end
end
deep[path.last] = 23
Is there a shorter way? Normally default initialization works neatly on hashes, but this only works for the first, level, maybe this could be done more dynamically.