Created
May 20, 2020 20:31
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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