Last active
December 18, 2015 10:48
-
-
Save jamescway/5770667 to your computer and use it in GitHub Desktop.
Find in nested hashes, prints key path recursively
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
def search_in_hash(hash, target, args={}, keys='ROOT') | |
find_key = (args[:find_key] == true) | |
hash.each do |key, value| | |
find_target = find_key ? key.to_s : value | |
if find_target == target | |
keys = "#{keys} -> '#{key}' => #{target}" | |
puts keys | |
keys = "" | |
end | |
if value.is_a?(Hash) | |
new_keys = "#{keys} -> '#{key}'" | |
search_in_hash(value, target, args, new_keys) | |
next | |
end | |
end | |
end | |
h = {:a => 1, :b => {:x => 11, :y => {"i" => 99}}, :c => 99} | |
search_in_hash(h, 99, {:find_key => false}) | |
#OUTPUT | |
# ROOT -> 'b' -> 'y' -> 'i' => 99 | |
# ROOT -> 'c' => 99 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment