在Rails中搜索嵌套散列中的键 [英] search for key in a nested hash in Rails
本文介绍了在Rails中搜索嵌套散列中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 myAuth
<$ p $对象中捕获了以下嵌套的哈希(来自Ominauth-Facebook) p>
< Ominauth :: AuthHash凭证
extra =#< Hashie :: Mash
raw_info =#< Hashie :: Mash email =myemail@gmail.com >>>
我想提取电子邮件,所以我使用:
myAuth ['extra'] ['raw_info'] ['email']
但是,我想搜索整个散列并在不知道确切的散列结构的情况下获取关键字 email
的值。我应该怎么办?
谢谢。 不知道这是否是最好的解决方案,但我会这样做:
h = {seal:5,test:3 ,回答:{nested:该死的,某事:{email:耶! }}}
def search_hash(h,search)
return h [search] if h.fetch(search,false)
h.keys.each do | K |
answer = search_hash(h [k],search)if h [k] .is_a?哈希
返回答案如果答案
结束
$ b $ false
结束
将search_hash(h,:email)
如果密钥存在或为false,则会返回该值。
I have the following nested hash (from Ominauth-Facebook) captured in an object called myAuth
<Ominauth::AuthHash credentials
extra=#<Hashie:: Mash
raw_info=#<Hashie::Mash email="myemail@gmail.com">>>
I would like to extract email, so I use:
myAuth['extra']['raw_info']['email']
However, I would like to search the entire hash and get the value for key email
without knowing exact hash structure. How should I go about it?
Thank you.
解决方案
Don't know if this is the best solution, but i would do:
h = {seal: 5, test: 3, answer: { nested: "damn", something: { email: "yay!" } } }
def search_hash(h, search)
return h[search] if h.fetch(search, false)
h.keys.each do |k|
answer = search_hash(h[k], search) if h[k].is_a? Hash
return answer if answer
end
false
end
puts search_hash(h, :email)
This will return the value if the key exists or false.
这篇关于在Rails中搜索嵌套散列中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文