问题
From psd.rb gem by LayerVault, I get a hash that contains all the layers and groups of the psd in nested hashes. Here is a gist of the hash. I want to retrieve a certain key from that hash. Is there a way to do this and store those keys values in an array?
回答1:
def values(hsh, key)
return [] if !hsh.kind_of? Hash
v = hsh[key] ? [hsh[key]] : []
hsh.values.select{|i| i.kind_of? Hash or i.kind_of? Array}.each do |val|
if val.kind_of? Hash
v+= values(val, key)
else
val.each {|i| v+= values(i, key)}
end
end
return v
end
puts values(h, :blending_mode).inspect # h is the Hash from your gist
# => ["normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal", "normal"]
来源:https://stackoverflow.com/questions/17990332/return-single-key-from-nested-hash-in-ruby