Generate nested hashes from strings and deep merging in ruby

后端 未结 1 1418
野趣味
野趣味 2021-01-06 17:11

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

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

I need to ge

相关标签:
1条回答
  • 2021-01-06 17:21

    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'] #=> {}
    
    0 讨论(0)
提交回复
热议问题