Skip to content

Instantly share code, notes, and snippets.

@clm-a
Created April 28, 2011 14:02
Show Gist options
  • Save clm-a/946399 to your computer and use it in GitHub Desktop.
Save clm-a/946399 to your computer and use it in GitHub Desktop.
Try on a nested hash
# http://rubyquicktips.tumblr.com/post/4601358354/using-try-with-a-hash-to-check-existence-of-a-key
hsh = { :existing_key =>
{
:existing_sub_key => :value
}
}
hsh.try(:[], :existing_key).try(:[], :existing_sub_key)
# => :value
hsh.try(:[], :unexisting_key).try(:[], :whatever) || "Default nested value"
# => "Default nested value"
hsh[:unexisting_key][:whatever] rescue 'Default'
# => "Default"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment