Skip to content

Instantly share code, notes, and snippets.

@forforf
Created October 24, 2011 16:43
Show Gist options
  • Save forforf/1309476 to your computer and use it in GitHub Desktop.
Save forforf/1309476 to your computer and use it in GitHub Desktop.
Find nested values within a hash
#find arbitrairly deep value based on keys
# {:a=> {:b=> {:c => 'C'}}}.find_deep(:a, :b, :c) #=> 'C'
class Hash
def find_deep(*keys)
find_deep_iter(self, keys)
end
def find_deep_iter(h, keys)
return h if keys.empty?
if h.respond_to? :keys
find_deep_iter(h[keys.shift], keys)
else #h isn't hash-like
keys.empty? ? h : nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment