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

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

    No need for monkey patching, just use Hashie gem: https://github.com/intridea/hashie#deepfind

    user = {
      name: { first: 'Bob', last: 'Boberts' },
      groups: [
        { name: 'Rubyists' },
        { name: 'Open source enthusiasts' }
      ]
    }
    
    user.extend Hashie::Extensions::DeepFind
    
    user.deep_find(:name)   #=> { first: 'Bob', last: 'Boberts' }
    

    For arbitrary Enumerable objects, there is another extension available, DeepLocate: https://github.com/intridea/hashie#deeplocate

提交回复
热议问题