本文介绍了通过按键名称从ruby中的多维散列提取特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个多维散列,并且在其中一个子散列中,我有一个key => value对,我需要通过key来检索。例子哈希:
h = {:x => 1,:y => 2,:z => {:a => {:k =>needle}}}
h = {:k =>针}
键总是:k,我需要获得针
我注意到在ruby 1.8中没有用于哈希的扁平化函数,但如果它在那里,我想我会做$ / b
$ b
h.flatten [:k]
谢谢
解决方案您可以随时编写自己的特定于任务的扩展程序,以便为您做一些肮脏的工作:
class哈希
def recursive_find_by_key(key)
#创建一堆哈希来搜索针头,
#最初是这个哈希
stack = [self]
#只要有更多草垛搜索...
while(to_search = stack.pop)
#...继续搜索这个特定的键...
to_search.each do | k,v |
#...并返回相应的值,如果找到。
return v if(k == key)
#如果这个值可以递归搜索...
if(v.respond_to?(:recursive_find_by_key))
#...将其推送到要搜索的地点列表中。
堆栈<< v
结束
结束
结束
结束
结束
您可以很简单地使用它:
h = {:x => 1,:y => ; 2:z => {:a => {:k =>needle}}}
puts h.recursive_find_by_key(:k).inspect
#= > 针
h = {:k =>needle}
puts h.recursive_find_by_key(:k).inspect
#=> needle
puts h.recursive_find_by_key(:foo).inspect
#=>无
let's say i have a multidimensional hash, and in one of the subhashes i have a key=>value pair which i need to retrieve by key. how can i do it?
example hashes:
h={:x=>1,:y=>2,:z=>{:a=>{:k=>"needle"}}}
h={:k=>"needle"}
key is always :k, and i need to get "needle"
i noticed that there is no "flatten" function for hashes in ruby 1.8, but if it'd be there, i imagine i'd just do
h.flatten[:k]
i imagine i need to write a recursive function for that?
thanks
解决方案
You can always write your own mission-specific extension to Hash which does the dirty work for you:
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
You can use this quite simply:
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
这篇关于通过按键名称从ruby中的多维散列提取特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
08-18 13:21