2015-12-14 81 views
2

我有這樣一個哈希:拼合哈希並連接鍵

{ 
"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" 
} 

我想與任何級別的嵌套工作的功能。我怎樣才能做到這一點在紅寶石?

+0

這個散列可以有多深?有限制嗎? –

+3

參考http://stackoverflow.com/questions/9647997/converting-a-nested-hash-into-a-flat-hash – sawa

+1

你在標題和文字中的描述是誤導性的。您不僅僅修改這些值。您也在修改密鑰。 – sawa

回答

2

改編這裏是一個遞歸方法,其中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