Created
April 28, 2011 14:02
-
-
Save clm-a/946399 to your computer and use it in GitHub Desktop.
Try on a nested hash
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
# 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