Last active
December 16, 2015 07:38
-
-
Save F-3r/5399735 to your computer and use it in GitHub Desktop.
HashTree
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
class HashTree < Hash | |
def self.new | |
super { |h, k| h[k] = new(&h.default_proc) } | |
end | |
def path=(*nodes, value) | |
k = nodes.shift | |
if nodes.empty? | |
self[k] = value | |
else | |
self[k].path=(*nodes, value) | |
end | |
end | |
def path(*nodes) | |
k = nodes.shift | |
if nodes.empty? | |
self[k] | |
else | |
self[k].path(*nodes) | |
end | |
end | |
end | |
h = HashTree.new | |
h[:a][:b][:c] | |
=> {} | |
h | |
=> {a: {b:{ c: {}}}} | |
h[:a][:b][:c] = 1000 | |
=> 1000 | |
h[:a][:b][:c] | |
=> 1000 | |
path = [:a,:b,:c] | |
=>[:a,:b,:c] | |
h.path(path) | |
=>1000 | |
h.path=(path, 2) | |
=>2 | |
h.path(path) | |
=>2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Lo choto de sobre-escribir
new
es que perdés un poco la interface que te proponeHash
. Si bien son objetos diferentes,new
debería (según creo) ser igual a la superclase.Podrías hacer algo como:
por otro lado, no haría falta decir:
HashTree.new(&h.default_proc)
, connew(&h.default_proc)
bastaría, porque el receptor del mensaje esself
, que esHashTree
.