2014-05-01 128 views
3

我有以下散列:紅寶石:加入哈希鍵

{ 
    a: { 
    b: { 
    c1: "c1 value", 
    c2: "c2 value", 
    c3: { 
     d: "d value 
    } 
    } 
} 

我怎麼能他轉換到下一個結果:

{ 
    "a.b.c1" => "c1 value", 
    "a.b.c2" => "c2 value", 
    "a.b.c3.d" => "d value" 
} 
+1

可能[將嵌套散列轉換爲平坦散列]副本(http://stackoverflow.com/questions/9647997/converting-a-nested-hash-into-a-flat-hash) – sawa

+0

@sawa你說得對,thx – ole

回答

5

這裏是一個modified解決方案:

h = { 
    a: { 
    b: { 
    c1: "c1 value", 
    c2: "c2 value", 
    c3: { 
     d: "d value" 
    } 
    } 
    } 
} 

def flatten_hash(h) 
    return { "" => h } unless h.is_a?(Hash) 
    Hash[h.map { |a,v1| flatten_hash(v1).map { |b,v2| [[a,b].map(&:to_s).delete_if(&:empty?).join('.'), v2] } }.flatten(1)] 
end 

p flatten_hash(h)