使用 Ruby/Rails 将嵌套散列展平为单个散列 [英] Flattening nested hash to a single hash with Ruby/Rails
本文介绍了使用 Ruby/Rails 将嵌套散列展平为单个散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想展平"(不是经典意义上的 .flatten
)具有不同深度级别的散列,如下所示:
I want to "flatten" (not in the classical sense of .flatten
) down a hash with varying levels of depth, like this:
{
:foo => "bar",
:hello => {
:world => "Hello World",
:bro => "What's up dude?",
},
:a => {
:b => {
:c => "d"
}
}
}
向下变成一层散列,所有嵌套的键合并成一个字符串,所以它会变成这样:
down into a hash with one single level, and all the nested keys merged into one string, so it would become this:
{
:foo => "bar",
:"hello.world" => "Hello World",
:"hello.bro" => "What's up dude?",
:"a.b.c" => "d"
}
但是我想不出一个好的方法来做到这一点.这有点像 Rails 添加到 Hashes 的 deep_
辅助函数,但并不完全相同.我知道递归是这里的最佳选择,但我从未在 Ruby 中编写过递归函数.
but I can't think of a good way to do it. It's a bit like the deep_
helper functions that Rails adds to Hashes, but not quite the same. I know recursion would be the way to go here, but I've never written a recursive function in Ruby.
推荐答案
你可以这样做:
def flatten_hash(hash)
hash.each_with_object({}) do |(k, v), h|
if v.is_a? Hash
flatten_hash(v).map do |h_k, h_v|
h["#{k}.#{h_k}".to_sym] = h_v
end
else
h[k] = v
end
end
end
flatten_hash(:foo => "bar",
:hello => {
:world => "Hello World",
:bro => "What's up dude?",
},
:a => {
:b => {
:c => "d"
}
})
# => {:foo=>"bar",
# => :"hello.world"=>"Hello World",
# => :"hello.bro"=>"What's up dude?",
# => :"a.b.c"=>"d"}
这篇关于使用 Ruby/Rails 将嵌套散列展平为单个散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文