假设我有一个多维哈希,并且在其中一个子哈希中我有一个key =>值对,我需要通过键检索。我怎么能这样做?
示例哈希:
h={:x=>1,:y=>2,:z=>{:a=>{:k=>"needle"}}}
h={:k=>"needle"}
键总是:k,我需要得到“针”
我注意到ruby 1.8中的哈希没有“flatten”功能,但是如果它在那里,我想我会做的
h.flatten[:k]
我想我需要为此编写一个递归函数?
感谢
答案 0 :(得分:9)
您可以随时为Hash编写自己的任务特定扩展,为您完成肮脏的工作:
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
答案 1 :(得分: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'