Can ruby deep search a hash/array for a particular key?

api, arrays, hash, json, ruby

Solution

Using `Enumerable#find`:

actions = [
  {'dummy' => true },
  {'dummy' => true },
  {'dummy' => true },
  {'lastBuiltRevision' => { "SHA1" => "123abc" }},
  {'dummy' => true },
]
actions.find { |h|
  h.has_key? 'lastBuiltRevision'
}['lastBuiltRevision']['SHA1']
# => "123abc"

UPDATE

Above code will throw `NoMethodError` if there's no matched item. Use follow code if you don't want get an exception.

rev = actions.find { |h| h.has_key? 'lastBuiltRevision' }
rev = rev['lastBuiltRevision']['SHA1'] if rev

Problem

I have some ruby code that gets a json from Jenkins that contains an array of n items. The item I want has a key called "lastBuiltRevision" I know I can loop through the array like so ``` actions.each do |action| if action["lastBuiltRevision"] lastSuccessfulRev = action["lastBuiltRevision"]["SHA1"] break end end ``` but that feels very clunky and devoid of the magic that I usually feel when working with ruby. I have only been tinkering with it for roughly a week now, and I feel that I may be missing something to make this easier/faster. Is there such a thing? or is manual iteration all I can do? I am kind of hoping for something like ``` lastSuccessfulRev = action.match("lastBuildRevision/SHA1") ```

Original source