在包含任意数量的嵌套散列和数组的散列深处查找键/值对 [英] Find key/value pairs deep inside a hash containing an arbitrary number of nested hashes and arrays

查看:47
本文介绍了在包含任意数量的嵌套散列和数组的散列深处查找键/值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Web 服务返回一个哈希,其中包含未知数量的嵌套哈希,其中一些包含一个数组,而数组又包含未知数量的嵌套哈希.

A web service is returning a hash that contains an unknown number of nested hashes, some of which contain an array, which in turn contains an unknown number of nested hashes.

有些键不是唯一的——即存在于多个嵌套散列中.

Some of the keys are not unique -- i.e. are present in more than one of the nested hashes.

然而,我真正关心的所有键都是唯一的.

However, all the keys that I actually care about are all unique.

有什么办法可以给顶级散列一个键,即使键值对深埋在这个泥潭中,也能取回它的值吗?

Is there someway I can give a key to the top-level hash, and get back it's value even if the key-value pair is buried deep in this morass?

(Web 服务是 Amazon Product Advertising API,根据结果数量和每个产品类别中允许的搜索类型,它提供的结果结构略有不同.)

(The web service is Amazon Product Advertising API, which slightly varies the structure of the results that it gives depending on the number of results and the search types permitted in each product category.)

推荐答案

这是一个简单的递归解决方案:

Here's a simple recursive solution:

def nested_hash_value(obj,key)
  if obj.respond_to?(:key?) && obj.key?(key)
    obj[key]
  elsif obj.respond_to?(:each)
    r = nil
    obj.find{ |*a| r=nested_hash_value(a.last,key) }
    r
  end
end

h = { foo:[1,2,[3,4],{a:{bar:42}}] }
p nested_hash_value(h,:bar)
#=> 42

这篇关于在包含任意数量的嵌套散列和数组的散列深处查找键/值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆