1

I have a database object in active record. If I call object.find(1).present? it returns false, but it exists. Calling !object.find(1).nil? returns true.

Why is this? I thought !nil == present?.

Monti
  • 643
  • 6
  • 18

2 Answers2

5

nil? and present? are not opposites.

Many things are both not present? and not nil?, such as an empty string or empty array.

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

[].present? # => false
[].nil? # => false
user229044
  • 232,980
  • 40
  • 330
  • 338
5

To better answer your question lets look at the implementation:

def present?
  !blank?
end

We don't see nil? mentioned here, just blank?, so lets check out blank? as well:

def blank?
  respond_to?(:empty?) ? !!empty? : !self
end

So essentially, if the object responds_to empty? it will call out to that for the result. Objects which have an empty? method include Array, Hash, String, and Set.

Further Reading

Community
  • 1
  • 1
Anthony Michael Cook
  • 1,082
  • 10
  • 16
  • It might be good to point out that in the case of String, `blank?` differs from `empty?` in that a string with all whitespace is blank but not empty. – mckeed Aug 26 '21 at 22:32