从字符串生成嵌套散列并在Ruby中进行深度合并 [英] Generate nested hashes from strings and deep merging in ruby
问题描述
我在JSON格式的数据库中有一个散列。例如
{
one=> {
two=> {
three=> {}
}
}
}
我需要生成这来自一个字符串。上面的例子将由字符串one.two.three生成。
首先,我该怎么做?
问题的第二部分。我会收到多个字符串 - 每个字符串都是最后一个字符串。所以,如果我得到one.two.three,那么one.two.four,我哈希是这样的:
{
one=> {
two=> {
three=> {},
four=> {}
}
}
}
如果我得到one.two.three两次,我想要最新的三值来覆盖那里。字符串也可以是任意长度的(例如one.two.three.four.five或者one)。希望这是有道理的?
要生成嵌套的哈希值:
hash = {}
one.two.three.split('。')。reduce(hash){| h,m | h [m] = {}}
puts hash#=> {one=> {two=> {three=> {}}}}
如果您没有安装rails,请安装activesupport gem:
gem install activesupport
然后将其包含到您的文件中:
require'active_support / core_ext / hash / deep_merge'
hash = {
one=> {
two=> {
three=> {}
}
}
} .deep_merge(another_hash)
对内部的访问将是:
$ p $ hash $ ['one'] ['two'] ['three']# => {}
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?
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'] #=> {}
这篇关于从字符串生成嵌套散列并在Ruby中进行深度合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!