Last active
September 26, 2016 19:39
-
-
Save TimothyClayton/84998ae9dc586965b5e9436ef096051d to your computer and use it in GitHub Desktop.
Set default value when blank values are potentially returned
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
# The immediate tendency is to go with a ternary, a la: | |
hash[:key].present? ? hash[:key] : 'default' | |
# To save a little on ABC complexity, I like `#presence`: | |
``` | |
>> h = { a: "I'm here" } | |
>> h[:a].presence || 'default' | |
"I'm here" | |
>> h = { a: nil } | |
>> h[:a].presence || 'default' | |
"default" | |
>> h = { a: '' } | |
>> h[:a].presence || 'default' | |
"default" | |
>> h = { a: [] } | |
>> h[:a].presence || 'default' | |
"default" | |
# Also works when hash does not have key | |
>> h[:b].presence || 'default' | |
"default" | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment