我只是有一个简单的问题,请考虑这段代码:
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] || 有关{}
有人可以帮帮我吗? 我觉得我错过了一些愚蠢的东西......
非常感谢
最佳答案
你可以这样做:
class Hash
def value_for((*keys, last), value)
_h = nil
keys.inject(self){|h, k| _h = h[k] ||= {}}
_h[last] = value
end
end
关于 ruby 嵌套哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14158987/