Last Updated: November 16, 2021
·
1.577K
· freesteph

Empty strings and ternary operators

In Ruby, an empty string does not evaluate to false. Hence if you wrote something like:

class User
  def greeting
    "Hey #{self.first_name || 'you'}"
  end
end

You'd end up with "Hey" even when first_name is empty, which, granted, is acceptable but not as nice as "Hey you".

After googling for return receiver if true, I finally found an extension Ruby On Rails provides on the Object class, called #presence. From the docs:

Returns the receiver if it's present otherwise returns nil.

Which makes it extremely useful for our example above, and you can now write:

class User
  def greeting
    "Hey #{self.first_name.presence || 'you'}"
  end
end

Very nice indeed.