eeeeeean
eeeeeean

Reputation: 1834

What is the meaning of `!!empty?`?

ActiveSupport extends Object with an instance method blank?:

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

Could !!empty? be written as empty? instead? Is this a stylistic choice so that it reads easily as a method returning a boolean? Or is there something else?

Upvotes: 3

Views: 147

Answers (5)

Stefan
Stefan

Reputation: 114218

In fact, it used to be empty?. Here's the commit that changed it to !!empty?: https://github.com/rails/rails/commit/126dc47665c65cd129967cbd8a5926dddd0aa514

From the comments:

Bartuz:
Why double !! ? It returns the TrueClass / FalseClass anynway

fxn:
Because it is a dynamic language and subject to polymorphism, you just can't rely on empty? returning singletons, what you need to guarantee is that you return one no matter what.

The "improved" implementation however is incomplete, because you could just as well implement ! to return a non-boolean value:

class Foo
  def !
    nil
  end
end

Foo.new.blank? #=> nil

To handle both methods (empty? and !), it should be implemented as:

!!(respond_to?(:empty?) ? empty? : !self)

Upvotes: 2

kimrgrey
kimrgrey

Reputation: 562

It is a common approach in Ruby to call !!(something). The result of the calculation will be boolean, not nil or something else:

!!(true) # true
!!(false) # false
!!(nil) # false

Upvotes: 3

NateSHolland
NateSHolland

Reputation: 1180

The reason for this is that !! coerces the response from empty to a boolean. Empty can be defined differently on different objects so it is possible that someone in rails could have defined .empty? to not return a boolean. Since .blank? needs to return a boolean the !! is needed to ensure that a boolean is returned.

Upvotes: 6

Leonel Galán
Leonel Galán

Reputation: 7167

!! is used to force falsey/truthy values to false/true:

irb(main):001:0> !!nil == false
=> true

Upvotes: 2

sawa
sawa

Reputation: 168209

It is a common way to convert a truthy versus falesy value into strict true and false.

Upvotes: 4

Related Questions