Last active
November 12, 2019 11:34
-
-
Save 0xradical/88dc53aefc29837a5fe01e51ac6c0520 to your computer and use it in GitHub Desktop.
deep_find.rb
This file contains 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
# return path for deep find in nested hashes | |
def deep_find(hash, term) | |
paths = [] | |
_deep_find(hash, term, root = "", paths) | |
paths | |
end | |
def _deep_find(hash, term, root, paths) | |
if hash.is_a?(Hash) | |
hash.each_pair do |k,v| | |
_deep_find(v, term, root == "" ? "#{k}" : root + ".#{k}", paths) | |
end | |
elsif hash.is_a?(Array) | |
hash.each_with_index do |item, index| | |
_deep_find(item, term, root + "[#{index}]", paths) | |
end | |
elsif hash == term | |
paths << root | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment