Iterate over a deeply nested level of hashes in Ruby

后端 未结 8 1744
眼角桃花
眼角桃花 2020-12-05 00:13

So I have a hash, and for each level of the hash, I want to store its key and value. The problem is, a value can be another hash array. Furthermore, that hash can contain ke

8条回答
  •  庸人自扰
    2020-12-05 00:34

    I recomend to use #deep_locate of hashie gem https://www.rubydoc.info/github/intridea/hashie/Hashie/Extensions/DeepLocate#deep_locate-instance_method

    little bit hacky always return false not to seeking

    hash.extend(Hashie::Extensions::DeepLocate)
    hash.deep_locate -> (key, value, object) do 
      # what you want to do here!
      # key: hash key
      # value: hash value
      # object: hash_object
      false # prevent to stop seeking
    end
    

提交回复
热议问题