Created
October 24, 2011 16:43
-
-
Save forforf/1309476 to your computer and use it in GitHub Desktop.
Find nested values within a hash
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
#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