Skip to content

Instantly share code, notes, and snippets.

@TimothyClayton
Last active September 26, 2016 19:39
Show Gist options
  • Save TimothyClayton/84998ae9dc586965b5e9436ef096051d to your computer and use it in GitHub Desktop.
Save TimothyClayton/84998ae9dc586965b5e9436ef096051d to your computer and use it in GitHub Desktop.
Set default value when blank values are potentially returned
# 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