从字符串生成嵌套哈希并在ruby中深度合并

Pla*_*tsy 3 ruby hash merge

我在JSON格式的数据库中有一个哈希.例如

{
  "one" => {
    "two" => {
      "three" => {}
    }
  } 
}
Run Code Online (Sandbox Code Playgroud)

我需要从字符串生成这个.上面的例子将从字符串"one.two.three"生成.

首先,我该怎么做?

第二部分问题.我将收到多个字符串 - 每个字符串构建在最后一个字符串上.所以,如果我得到"one.two.three",然后是"one.two.four",我就是这样:

{
  "one" => {
    "two" => {
      "three" => {},
      "four" => {}
    }
  } 
}
Run Code Online (Sandbox Code Playgroud)

如果我两次获得"one.two.three",我希望最新的"三"值覆盖那里的内容.字符串也可以是任何长度(例如"one.two.three.four.five"或只是"one").希望这有道理吗?

meg*_*gas 13

要生成嵌套哈希:

hash = {}

"one.two.three".split('.').reduce(hash) { |h,m| h[m] = {} }

puts hash #=> {"one"=>{"two"=>{"three"=>{}}}}
Run Code Online (Sandbox Code Playgroud)

如果您没有安装rails,请安装activesupport gem:

gem install activesupport
Run Code Online (Sandbox Code Playgroud)

然后将其包含在您的文件中:

require 'active_support/core_ext/hash/deep_merge'

hash = {
  "one" => {
    "two" => {
      "three" => {}
    }
  } 
}.deep_merge(another_hash)
Run Code Online (Sandbox Code Playgroud)

对内部的访问将是:

hash['one']['two']['three'] #=> {}
Run Code Online (Sandbox Code Playgroud)