Skip to content

Instantly share code, notes, and snippets.

@bricker
Last active August 29, 2015 14:17
Show Gist options
  • Save bricker/51595b9461b387f82389 to your computer and use it in GitHub Desktop.
Save bricker/51595b9461b387f82389 to your computer and use it in GitHub Desktop.
module RecursiveKeyCheck
def recursive_key?(key)
return true if key?(key)
self.each do |_, v|
if v.is_a?(Hash)
return true if v.recursive_key?(key)
end
end
return false
end
end
class Hash; include RecursiveKeyCheck; end
hsh1 = { a: 1, b: 2 }
hsh2 = { b: { c: { d: { a: 1 } } }, e: 2, f: { a: 3 } }
hsh3 = { b: { c: { d: { z: 1 } } }, e: 2, f: { x: 3 } }
puts hsh1.recursive_key?(:a) # true
puts hsh2.recursive_key?(:a) # true
puts hsh3.recursive_key?(:a) # false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment