What is the difference between using `.exists?` and `.present?` in Ruby?

What is the difference between using .exists? and .present? in Ruby?

I want to ensure I’m using them correctly and understand any subtle differences. They seem to serve the same purpose—checking if an object field is defined—when used in the console. However, I couldn’t find much information online.

Can someone explain when to use Ruby present vs. .exists? and highlight their key differences?

Clarification on .exists? : The .exists? method is typically used to check the existence of a record in a database when dealing with ActiveRecord (in Rails) or checking whether a file exists in the filesystem. For example:

User.exists?(id: 1) This checks if a user with ID 1 exists in the database. It returns true or false based on the existence of the record.

In the context of files: File.exists?("path/to/file.txt") This checks if a file exists at the specified path.

Clarification on .present? :

On the other hand, .present? is used to check if an object is not nil or an empty object (such as an empty string, empty array, etc.). It’s most commonly used in Rails and is essentially the opposite of .blank?.

Here’s how you would typically use .present?:

"hello".present?   #=> true
"".present?        #=> false
nil.present?       #=> false

In Rails, you can use .present? on objects like strings, arrays, hashes, etc., to check if they have meaningful content. It’s not just checking for nil; it also checks if the object is empty.

The key difference is that .exists? is mostly used in ActiveRecord (or file system checks) to verify if something exists in a database or file system, while .present? is a general-purpose check to see if an object has a value, i.e., it’s not nil or empty.

In Rails or when dealing with Ruby objects, use .present? to check for meaningful content. If you’re querying for a database record or checking the existence of a file, you’ll use .exists?.