Created
June 8, 2012 06:50
-
-
Save mschuerig/2894061 to your computer and use it in GitHub Desktop.
Safely access an element in a nested hash by its path.
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
class Hash | |
# Safely access an element in a nested hash by its path. | |
# If any of the intervening hashes is not present, nil is returned. | |
def at(*path) | |
val = self | |
path.each do |k| | |
val = val[k] | |
return nil unless val | |
end | |
val | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment