TWIL is our weekly series designed to foster a culture of continuous learning in software development. This week, Katie takes us through the elegantly simple intricacies of Ruby #presence, a nuanced method that sifts out the emptiness and returns either the value itself or nil
.
Ruby #presence
Using thing.presence
vs the truthiness/falsiness of thing
directly: #presence
returns the value or nil but importantly excludes empty values.
It is essentially just shorthand for thing.present? ? thing : nil
.
# Empty string
> "" ? "truthy" : "falsy"
"truthy"
> "".present?
false
> "".presence
nil
# Empty array
> [] ? "truthy" : "falsy"
"truthy"
> [].present?
false
> [].presence
nil
# Non-empty string
> "thing" ? "truthy" : "falsy"
"truthy"
> "thing".present?
true
> "thing".presence
"thing"
# Non-empty array
> [1,2,3] ? "truthy" : "falsy"
"truthy"
> [1,2,3].present?
true
> [1,2,3].presence
[1, 2, 3]
# Nil
> nil ? "truthy" : "falsy"
"falsy"
> nil.present?
false
> nil.presence
nil
# True
> true ? "truthy" : "falsy"
"truthy"
> true.present?
true
> true.presence
true
# False
> false ? "truthy" : "falsy"
"falsy"
> false.present?
false
> false.presence
nil
Resources
- Ruby