Skip to content

Instantly share code, notes, and snippets.

@chrisb
Created December 14, 2010 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisb/741311 to your computer and use it in GitHub Desktop.
Save chrisb/741311 to your computer and use it in GitHub Desktop.
Hash extension for safe access to possibly undefined elements
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