Skip to content

Instantly share code, notes, and snippets.

@pda
Created September 15, 2022 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pda/d512a37a7c6575f28ea4e7e11a093574 to your computer and use it in GitHub Desktop.
Save pda/d512a37a7c6575f28ea4e7e11a093574 to your computer and use it in GitHub Desktop.
Ruby recursive Hash search
haystack = {
action: "greeting",
scope: "world",
things: [
{ x: "city" },
{ x: "country" },
{ x: "world" },
]
}
def search(needle, haystack, path = [], matches = [])
case haystack
when Hash
haystack.each_pair { |k, v| search(needle, v, path + [k], matches) }
when Array
haystack.each_with_index { |v, i| search(needle, v, path + [i], matches) }
else
matches << path.join(".") if haystack == needle
end
matches
end
p search("world", haystack)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment