让我们说我有一个多维散列,并且在subhashes i中的一个有一个钥匙=>值对我需要通过键来检索。我如何做呢?

例如散列:

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

键总是:k,以及我需要得到 “针”

我注意到,有使用Ruby 1.8哈希没有“扁平化”的功能,但如果它会在那里,我想我只是做

h.flatten[:k]

我想象我需要编写一个递归函数是什么?

感谢

有帮助吗?

解决方案

您可以编写自己的具体任务扩展到哈希其干这个苦差事你:

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

其他提示

如果您需要简单地获取关键值,但不知道密钥有多深,使用该段

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'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top