l'estrazione di valore specifico da un hash multidimensionale in Ruby dal nome della chiave
-
19-09-2019 - |
Domanda
Diciamo che avere un hash multidimensionale, e in una delle subhashes ho una coppia chiave-valore => che ho bisogno di recuperare a chiave. Come posso fare?
Esempio hash:
h={:x=>1,:y=>2,:z=>{:a=>{:k=>"needle"}}}
h={:k=>"needle"}
chiave è sempre: k, e ho bisogno di ottenere "ago"
ho notato che non esiste una funzione "appiattire" per gli hash in Ruby 1.8, ma se sarebbe lì, immagino che avevo appena fare
h.flatten[:k]
immagino ho bisogno di scrivere una funzione ricorsiva per questo?
grazie
Soluzione
Si può sempre scrivere il proprio estensione specifica missione di Hash che fa il lavoro sporco per voi:
class Hash
def recursive_find_by_key(key)
# Create a stack of hashes to search through for the needle which
# is initially this hash
stack = [ self ]
# So long as there are more haystacks to search...
while (to_search = stack.pop)
# ...keep searching for this particular key...
to_search.each do |k, v|
# ...and return the corresponding value if it is found.
return v if (k == key)
# If this value can be recursively searched...
if (v.respond_to?(:recursive_find_by_key))
# ...push that on to the list of places to search.
stack << v
end
end
end
end
end
È possibile utilizzare questo molto semplicemente:
h={:x=>1,:y=>2,:z=>{:a=>{:k=>"needle"}}}
puts h.recursive_find_by_key(:k).inspect
# => "needle"
h={:k=>"needle"}
puts h.recursive_find_by_key(:k).inspect
# => "needle"
puts h.recursive_find_by_key(:foo).inspect
# => nil
Altri suggerimenti
Se avete bisogno semplicemente di recuperare il valore della chiave, ma non so quanto è profonda la chiave è, utilizzare questo frammento
def find_tag_val(hash, tag)
hash.map do |k, v|
return v if k.to_sym == tag
vr = find_tag_val(v, tag) if v.kind_of?(Hash)
return vr if vr
end
nil #othervice
end
h = {message: { key: 'val'}}
find_tag_val(h, :key) #=> 'val'