Generate nested hashes from strings and deep mergi

2019-02-15 00:10发布

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

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

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

Firstly how would I do this?

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" => {}
    }
  } 
}

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?

标签: ruby hash merge
1条回答
Ridiculous、
2楼-- · 2019-02-15 00:51

To generate nested hash:

hash = {}

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

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

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)

The access to the internals would be:

hash['one']['two']['three'] #=> {}
查看更多
登录 后发表回答