我有一个简单的问题,考虑一下这段代码:
class Hash
def value_for(keys, value)
common = self
while keys.size > 1 and !common.nil?
common = common[keys.shift] || { }
end
common[keys.last] = value
end
end
使用这段代码,我希望能够通过传递嵌套节点的数组和应该分配的值来创建嵌套哈希。
它应该像下面这样工作:
hash = {
"message" => "hello world"
}
hash.value_for [ "nested", "message" ], "hello world"
hash
#=> {
"message" => "hello world",
"nested" => {
"message" => "hello world"
}
}
hash.value_for [ "second", "nested", "message" ], "hello world"
hash
#=> {
"message" => "hello world",
"nested" => {
"message" => "hello world"
},
"second" => {
"nested" => {
"message" => "hello world"
}
}
}
由于某种原因,我的代码在创建新哈希时不起作用。我怀疑它与common = common[keys.shift] || { }
有人能帮助我吗?我觉得我错过了一些愚蠢的东西......
非常感谢