Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a function in Ruby to traverse dynamic multi level hashes where all that is known is the required key?

Is there a way to access my_key value without knowing the path to where the key value is stored
using out the box ruby methods?

You will see that the two scenarios below store the my_key in different
places. These hashes structure will always be dynamic so you can’t predict the
exact path to access my_key but the keys name is always know. I’ve seen .dig which is very close to what’s needed just with the added functionality of being able to traverse multi level hashes and arrays, effectively like a wildcard.

scenario_1 = {
  level_1a: {
    level2: [
      {
        level3: {
          my_key: "here"
        }
      }
    ]
  },  
  level_1b: "test"
}

scenario_2 = {
  level_1a: {
    my_key: "here"
  },  
  level_1b: "test"
}

If not possible through out the box ruby; are there any known gems that add this functionality or do you think it’s best just implementing your own custom recursive deep scan method?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The dig-deep gem seems to be what you are looking for:

require 'dig-deep'

scenario_1.dig_deep(:my_key)
=> "here"
scenario_2.dig_deep(:my_key)
=> "here"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading