["sport", "gaming", "other"], "duration" => 312, "locations" => { "-6ren">
gpt4 book ai didi

ruby - 展平散列并连接键

转载 作者:数据小太阳 更新时间:2023-10-29 08:44:30 24 4
gpt4 key购买 nike

我有这样一个哈希:

{
"category" => ["sport", "gaming", "other"],
"duration" => 312,
"locations" => {
"688CQQ" => {"country" => "France", "state" => "Rhône-Alpes"},
"aUZCAQ" => {"country" => "France", "state" => "Île de France"}
}
}

如果值是散列,我想通过展平值将其减少为散列而不嵌套。在最终值中,我应该只有整数、字符串或数组,如下所示:

{
"category" => ["sport", "gaming", "other"],
"duration" => 312,
"locations_688CQQ_country" => "France",
"locations_688CQQ_state" => "Rhône-Alpes",
"locations_aUZCAQ_country" => "France",
"locations_aUZCAQ_state" => "Île de France"
}

我想要一个适用于任何嵌套级别的函数。我如何在 ruby​​ 中做到这一点?

最佳答案

改编自https://stackoverflow.com/a/9648515/311744

def flat_hash(h, f=nil, g={})
return g.update({ f => h }) unless h.is_a? Hash
h.each { |k, r| flat_hash(r, [f,k].compact.join('_'), g) }
g
end

关于ruby - 展平散列并连接键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34270973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com