0

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?

Jake McAllister
  • 1,037
  • 3
  • 12
  • 29
  • The Hashie gem has many additions, including [DeepFind](https://github.com/hashie/hashie#deepfind) – Stefan May 19 '22 at 14:17

1 Answers1

2

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"
Casper
  • 33,403
  • 4
  • 84
  • 79