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

Frank Valcarcel speaking at Denver Startup Week 2018 on healthcare technology and HIPAA compliance, highlighting the digital revolution in healthcare IT
October 5, 2018 • Frank Valcarcel

Scaling Healthcare Technologies at DSW 2018

Discover the transformative journey of healthcare technology at Denver Startup Week 2018 with Frank . Dive into the world of healthcare software, product management, and the critical balance between innovation and HIPAA compliance.

August 18, 2024 • Frank Valcarcel

What makes Enterprise Software Development Different?

Enterprise software powers large organizations, handling complex tasks across departments. From robust security to scalability, these solutions face unique challenges. Explore what makes software “enterprise-ready” and how to choose the right development approach for your business.