Skip to content

Instantly share code, notes, and snippets.

@0xradical
Last active November 12, 2019 11:34
Show Gist options
  • Save 0xradical/88dc53aefc29837a5fe01e51ac6c0520 to your computer and use it in GitHub Desktop.
Save 0xradical/88dc53aefc29837a5fe01e51ac6c0520 to your computer and use it in GitHub Desktop.
deep_find.rb
# 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