Skip to content

Instantly share code, notes, and snippets.

@yepitschunked
Created June 19, 2013 00:34
Show Gist options
  • Save yepitschunked/5810785 to your computer and use it in GitHub Desktop.
Save yepitschunked/5810785 to your computer and use it in GitHub Desktop.
Autovivifying hash - accessing a key automatically creates a hash at that key
autovivifying = proc {|x| proc { Hash.new {|h,k| h[k] = x.call(x).call } } }.call(proc {|x| proc { Hash.new {|h,k| h[k] = x.call(x).call } } }).call
[53] pry(main)> autovivifying[:foo]
=> {}
[54] pry(main)> autovivifying[:foo][:bar]
=> {}
[55] pry(main)> autovivifying[:foo][:bar][:baz]
=> {}
[56] pry(main)> autovivifying
=> {:foo=>{:bar=>{:baz=>{}}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment