Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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