我想创建一个“配置”类,在散列和树之间的某个地方起作用。它只是用于存储可以具有上下文的全局值。这是什么样的哈希式/树状构造调用?
下面是我如何使用它:
Config.get("root.parent.child_b") #=> "value"
这里的类可能是什么样子:
class Construct
def get(path)
# split path by "."
# search tree for nodes
end
def set(key, value)
# split path by "."
# create tree node if necessary
# set tree value
end
def tree
{
:root => {
:parent => {
:child_a => "value",
:child_b => "another value"
},
:another_parent => {
:something => {
:nesting => "goes on and on"
}
}
}
}
end
end
是否有这种东西的名称,哈希和树之间的某个地方(而不是计算机科学专业)?基本上是一个类似树的接口。
东西输出是这样的:
t = TreeHash.new
t.set("root.parent.child_a", "value")
t.set("root.parent.child_b", "another value")
所需的输出格式:
t.get("root.parent.child_a") #=> "value"
t.get("root") #=> {"parent" => {"child_a" => "value", "child_b" => "another value"}}
,而不是这样的:
t.get("root") #=> nil
或本(你从通过调用获得的价值{}.value
)
t.get("root") #=> {"parent" => {"child_a" => {}, "child_b" => {}}}
这真棒。 – 2010-06-05 22:48:41
任何想法如何添加a)所以叶节点不是哈希值,它们是值(基本上意味着除去'attr_accessor:value'),和b)所以'get(“root”)'或任何级别返回下面的树而不是null如果它不是叶节点?试图实现这一点,但它增加了很多代码/复杂性,也许你知道一些内线技巧。我已经用示例输出更新了这个问题。 – 2010-06-05 23:30:52
据我看到它是删除代码,而不是添加:) – samuil 2010-06-06 08:28:18