Ruby 展平散列并连接键
我有这样一个杂凑:Ruby 展平散列并连接键,ruby,hash,flatten,Ruby,Hash,Flatten,我有这样一个杂凑: { "category" => ["sport", "gaming", "other"], "duration" => 312, "locations" => { "688CQQ" => {"country" => "France", "state" => "Rhône-Alpes"}, "aUZCAQ" => {"country" => "France", "state" => "Île de F
{
"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中做到这一点?改编自
这里是一种递归方法,
h
是您的哈希
def flat_hash(h)
h.reduce({}) do |a, (k,v)|
tmp = v.is_a?(Hash) ? flat_hash(v).map { |k2,v2| ["#{k}_#{k2}",v2]}.to_h : { k => v }
a.merge(tmp)
end
end
改编自
请原谅,我在这里继续讲下去
class ::Hash
def flat_hash(j='_', h=self, f=nil, g={})
return g.update({ f => h }) unless h.is_a? Hash
h.each { |k, r| flat_hash(j, r, [f,k].compact.join(j), g) }
g
end
end
现在我们可以做了
irb> {'foo' =>{'bar'=>{'squee'=>'woot'}}}.flat_hash('')
=> {"foobarsquee"=>"woot"}
你欠互联网甲骨文一个'!'方法。此哈希可以有多深?是否有限制?参见标题和正文中的描述,这是误导性的。您不仅在修改值。您也在修改这些键。@sawa确实如此。改名
irb> {'foo' =>{'bar'=>{'squee'=>'woot'}}}.flat_hash('')
=> {"foobarsquee"=>"woot"}