Find key/value pairs deep inside a hash containing an arbitrary number of nested hashes and arrays

前端 未结 9 1063
天涯浪人
天涯浪人 2020-12-02 20:12

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

9条回答
  •  长情又很酷
    2020-12-02 20:49

    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
    

提交回复
热议问题