Pergunta

digamos que eu tenha um hash multidimensional e em um dos subhashes eu tenha um par chave=>valor que preciso recuperar por chave.como eu posso fazer isso?

exemplo de hashes:

h={:x=>1,:y=>2,:z=>{:a=>{:k=>"needle"}}}
h={:k=>"needle"}

a chave é sempre :k, e preciso pegar a "agulha"

notei que não há função "achatar" para hashes no Ruby 1.8, mas se estivesse lá, imagino que faria

h.flatten[:k]

imagino que preciso escrever uma função recursiva para isso?

obrigado

Foi útil?

Solução

Você sempre pode escrever sua própria extensão específica da missão para Hash, que faz o trabalho sujo para você:

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

Você pode usar isso de forma bastante simples:

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

Outras dicas

Se você precisa simplesmente buscar o valor da chave, mas não sabe a profundidade da chave, use este snippet

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'
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top