perseverance perseverance - 22 days ago 4x
Ruby Question

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

I want to make sure I'm using them for the correct occasion and want to know of any subtleties. They seem to function the same way, which is to check to see if a object field has been defined, when I use them via the console and there isn't a whole lot information online when I did a google search. Thanks!

pje pje

To clarify: neither present? nor exists? are "pure" ruby—they're both from Rails-land.


present? is an ActiveSupport extension to Object. It's usually used as a test for an object's general "falseyness". From the documentation:

An object is present if it’s not blank?. An object is blank if it’s false, empty, or a whitespace string.

So, for example:

[ "", " ", false, nil, [], {} ].all?(&:blank?)
# => true


exists? is from ActiveResource. From its documentation:

Asserts the existence of a resource, returning true if the resource is found.

Note.create(:title => 'Hello, world.', :body => 'Nothing more for now...')
Note.exists?(1) # => true