0

多次元ハッシュがあり、サブハッシュの1つに、キーで取得する必要のあるkey=>valueのペアがあるとします。どうすればいいですか?

ハッシュの例:

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

キーは常に:kであり、「針」を取得する必要があります

ruby 1.8にはハッシュの「フラット化」機能がないことに気づきましたが、それがあれば、私はただやるだけだと思います

h.flatten[:k]

そのために再帰関数を書く必要があると思いますか?

ありがとう

4

2 に答える 2

9

あなたはいつでもあなたのために汚い仕事をするハッシュにあなた自身のミッション特有の拡張を書くことができます:

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

これは非常に簡単に使用できます。

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
于 2010-02-10T19:49:46.110 に答える
2

単にキー値をフェッチする必要があるが、キーの深さがわからない場合は、このスニペットを使用してください

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'
于 2013-11-13T07:48:31.517 に答える