back

!! (The double bang / double not) in Ruby

!! (aka double bang / double not / double exclamation) is a basic technique used occasionally in ruby to make code a bit shorter. But, like most things that seem to make things simpler, there’s a caveat.

Resful Authentication: !!current_user

Acts as paranoid: !!read_attribute(:deleted_at)

So it looks like people use !! in cases where the code is looking at something that is not bool true or false, but something is there or not there.

Another use is to make sure that methods ending in ? return bools rather than objects, as recommended in the second blog post below. For example, bored? could return either a) a boring object or nil or b) true or false. In a case where you were doing something like me = fool.bored? it seems reasonable to expect that me would not be nil or a boring object, but true or false.

So rather than returning self.boring_object you might return !!self.boring_object in the bored? method definition for the class Foo.

Note that in a case where current_user was already sometimes going to be true or false, you wouldn’t want to use this, as Evgeny points in a comment on the first blog post below. This is because false.nil? == false.

E.g.

c.f.
Ruby !! and bangbang your nil is dead
This article talks about double bang as well, and how not to use it

December 09, 2008