Created
December 14, 2010 23:13
-
-
Save chrisb/741311 to your computer and use it in GitHub Desktop.
Hash extension for safe access to possibly undefined elements
This file contains hidden or 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 | |
def value_at(*keys) | |
begin | |
memo = self.dup | |
keys.each { |key| memo = memo[key] } | |
memo | |
rescue | |
nil | |
end | |
end | |
end | |
hsh = { :parent => { :child => 'sally' }} | |
puts hsh.value_at :parent, :child # => 'sally' | |
puts hsh.value_at :foo, :bar # => nil |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment