从字符串生成嵌套哈希并在 ruby​​ 中深度合并 [英] Generate nested hashes from strings and deep merging in ruby

查看:23
本文介绍了从字符串生成嵌套哈希并在 ruby​​ 中深度合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a hash in the database in JSON format. eg

{
  "one" => {
    "two" => {
      "three" => {}
    }
  } 
}

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

I need to generate this from a string. The above example would be generated from the string "one.two.three".

首先我该怎么做?

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

Second part of the problem. I will be receiving multiple strings - each one building on the last. So if I get "one.two.three", then "one.two.four", I hash to be this:

{
  "one" => {
    "two" => {
      "three" => {},
      "four" => {}
    }
  } 
}

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

And if I get "one.two.three" twice, I want the latest "three" value to override what was there. Strings can also be of any length (e.g. "one.two.three.four.five" or just "one"). Hopefully that makes sense?

推荐答案

生成嵌套散列:

hash = {}

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

puts hash #=> {"one"=>{"two"=>{"three"=>{}}}}

如果你没有安装 rails 然后安装 activesupport gem:

If you don't have rails installed then install activesupport gem:

gem install activesupport

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

Then include it into your file:

require 'active_support/core_ext/hash/deep_merge'

hash = {
  "one" => {
    "two" => {
      "three" => {}
    }
  } 
}.deep_merge(another_hash)

对内部的访问将是:

hash['one']['two']['three'] #=> {}

这篇关于从字符串生成嵌套哈希并在 ruby​​ 中深度合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆