Created
September 15, 2022 11:32
-
-
Save pda/d512a37a7c6575f28ea4e7e11a093574 to your computer and use it in GitHub Desktop.
Ruby recursive Hash search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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