Created
June 19, 2013 00:34
-
-
Save yepitschunked/5810785 to your computer and use it in GitHub Desktop.
Autovivifying hash - accessing a key automatically creates a hash at that key
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
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