ruby嵌套哈希

时间:2013-01-04 14:27:58

标签: ruby algorithm hashmap nested

我刚才有一个简单的问题,请考虑这段代码:

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] || { }

有关 是的,有人能帮帮我吗? 我感觉我错过了一些愚蠢的事情......

非常感谢

3 个答案:

答案 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

您的代码存在以下问题:

  1. 要实现您尝试的操作,您需要以相反的顺序遍历键,因为键[i]取决于键的值[i + 1]
  2. 您需要为每个键创建一个新哈希,而common[keys.shift]实际上是一个值,您应该添加另一个嵌套级别。
  3. 希望这有帮助。

答案 2 :(得分:0)

require 'xkeys'
hash = { 
    "message" => "hello world"
}.extend XKeys::Hash
hash["nested", "message"] = "hello world"
hash["second", "nested", "message"] = "hello world"