/ 猿问

# 将嵌套的哈希转换为平面哈希

2019-11-18 18:24:20

{

:a => {

:b => {:c => 1, :d => 2},

:e => 3,

},

:f => 4,

}

{

[:a, :b, :c] => 1,

[:a, :b, :d] => 2,

[:a, :e] => 3,

[:f] => 4,

}

## 3 回答

def flat_hash(h,f=[],g={})

return g.update({ f=>h }) unless h.is_a? Hash

h.each { |k,r| flat_hash(r,f+[k],g) }

g

end

h = { :a => { :b => { :c => 1,

:d => 2 },

:e => 3 },

:f => 4 }

flat_hash(h) #=> {[:a, :b, :c]=>1, [:a, :b, :d]=>2, [:a, :e]=>3, [:f]=>4}

def flat_hash(h, k = [])

new_hash = {}

h.each_pair do |key, val|

if val.is_a?(Hash)

new_hash.merge!(flat_hash(val, k + [key]))

else

new_hash[k + [key]] = val

end

end

new_hash

end

def flat_hash(hash, k = [])

return {k => hash} unless hash.is_a?(Hash)

hash.inject({}){ |h, v| h.merge! flat_hash(v[-1], k + [v[0]]) }

end

def flatten(hash)

return {[] => hash} if !hash.is_a?(Hash)

map = {}

hash.each_pair do |key1, value1|

flatten(value1).each_pair do |key2, value2|

map[[key1] + key2] = value2

end

end

return map

end

{[:a, :b, :c]=>1, [:a, :b, :d]=>2, [:a, :e]=>3, [:f]=>4}

• 3 回答
• 0 关注
• 162 浏览

0/150