user2012677
user2012677

Reputation: 5745

Comparison of !! operator vs present?

In Ruby is there an advantage to call present?

my_value.present?

vs !!

!!my_value

Upvotes: 0

Views: 3267

Answers (1)

lurker
lurker

Reputation: 58284

.present? is part of Rails, not a part of a standard Ruby class library. The Rails documentation for .present? says that it's true if the object is "not blank". It's often used to determine of a database attribute has an actual value other than nil or blank.

> x = ' '
> x.present?
false
> x = nil
> x.present?
false

!! is two ! together, a standard Ruby operator. The ! is the Ruby logical "not" operator. A blank value is truthy in Ruby. Using two ! together lets you take a value in Ruby and get a simple boolean true or false depending upon whether the value is truthy or falsey.

> x = ' '
> !!x
true    # a blank is truthy
> x = nil
> !!x
false   # nil is falsey

Upvotes: 5

Related Questions