我刚才有一个简单的问题,请考虑这段代码:
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] || { }
非常感谢
答案 0 :(得分:1)
你可以这样做:
class Hash
def value_for((*keys, last), value)
_h = nil
keys.inject(self){|h, k| _h = h[k] ||= {}}
_h[last] = value
end
end
答案 1 :(得分:0)
这是一个有效的代码示例:
class Hash
def value_for(keys, value)
common = {}
common[keys.last] = value
(keys.size - 2).downto(0).each do |index|
common[keys[index]] = {keys[index+1] => common[keys[index+1]]}
end
return common
end
end
您的代码存在以下问题:
common[keys.shift]
实际上是一个值,您应该添加另一个嵌套级别。 希望这有帮助。
答案 2 :(得分:0)
require 'xkeys'
hash = {
"message" => "hello world"
}.extend XKeys::Hash
hash["nested", "message"] = "hello world"
hash["second", "nested", "message"] = "hello world"