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

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

问题描述

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.

某些键不唯一 - 即处于嵌套哈希的多于一个present

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服务是亚马逊的商品广告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天全站免登陆