Skip to content

Instantly share code, notes, and snippets.

@jamescway
Last active December 18, 2015 10:48
Show Gist options
  • Save jamescway/5770667 to your computer and use it in GitHub Desktop.
Save jamescway/5770667 to your computer and use it in GitHub Desktop.
Find in nested hashes, prints key path recursively
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