Skip to Main Content
TWIL
Ruby
A screenshot of Ruby code featuring the #presence method, with text highlighting how it simplifies identifying `nil` values.

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
Katie Linero's profile picture
Katie Linero

Senior Software Engineer

Related Posts

Dynamic team of software developers from Cuttlesoft, highlighting their organizational maturity enabled by their re-branded image.
August 18, 2022 • Frank Valcarcel

The New Cuttlesoft

To reimagine Cuttlesoft’s brand, we partnered with the experts at Focus Lab. With their guidance, we identified the ways Cuttlesoft was failing to meet its full potential.

A snapshot of Emily’s guide on using `patch-package` to manage Node Module bugs, featured in this week's TWIL blog post.
July 5, 2022 • Frank Valcarcel

TWIL 2022-07-01

Learn the art of Patching Node Modules in JavaScript this week on TWIL. Discover how `patch-package` can simplify bug fixes in your dependencies without the need for forking.