Skip to content

Instantly share code, notes, and snippets.

@flynn1982
Created May 20, 2020 20:31
Show Gist options
  • Save flynn1982/c25dfc83bea5afb86661d29cb7c66d1f to your computer and use it in GitHub Desktop.
Save flynn1982/c25dfc83bea5afb86661d29cb7c66d1f to your computer and use it in GitHub Desktop.
Ruby Autovivifying (Nested Hashes without having to declare the hashes in the tree first)
def autovivifying_hash
Hash.new {|ht,k| ht[k] = autovivifying_hash}
end
hash = autovivifying_hash
hash['a']['b']['c']['d']['e'] = 'hello'
puts hash['c']
puts hash['a']
puts hash['b']
puts hash['a']['b']
puts hash
=>
{}
{"b"=>"hello"}
{}
hello
{"a"=>{"b"=>"hello"}, "c"=>{}, "b"=>{}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment