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

前端 未结 9 1061
天涯浪人
天涯浪人 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:56

    Combining a few of the answers and comments above:

    class Hash
      def deep_find(key, object=self, found=nil)
        if object.respond_to?(:key?) && object.key?(key)
          return object[key]
        elsif object.is_a? Enumerable
          object.find { |*a| found = deep_find(key, a.last) }
          return found
        end
      end
    end
    

提交回复
热议问题