0

我有一个嵌套哈希:

hash = {
  "a" => "a",
  "b" => {
    "c" => "c",
    "d" => {
      "e" => "e"
    }
  }
}

我有一个哈希:

new_value = {
  "b.d.e" => "new value"
}

我需要某种“神奇”函数来替换 处的哈希值hash["b"]["d"]["e"],例如:

magical_function(hash, new_value)
#=> hash = {
      "a" => "a",
      "b" => {
        "c" => "c",
        "d" => {
          "e" => "new value"
        }
      }
    }

我不知道怎么做。有人可以帮忙吗?

4

2 回答 2

6

如果以直截了当的方式实现它并不神奇:

merge_hash.each do |key, value|
  parts = key.split('.')
  leaf = parts.pop

  target = parts.inject(hash) do |h, k|
    h[k] ||= { }
  end

  target[leaf] = value
end
于 2012-11-22T16:07:22.307 回答
1

这是另一个解决方案:

class Hash
  def replace_value(*keys, value)
    current = self
    current = current[keys.shift] while keys.size > 1
    current[keys.last] = value
  end
end

通过调用来调用hash.replace_value("b","d","e", "new_value")

于 2012-11-22T16:22:42.490 回答