A collection of computer systems and programming tips that you may find useful.
 
Brought to you by Craic Computing LLC, a bioinformatics consulting company.

Tuesday, October 19, 2010

!! in Ruby

I noticed this odd looking construct in Rick Olsen's restful_authentication plugin a while back:
!!current_user

At face value it appears to be a 'double not' operation on the variable current_user. But that didn't make much sense to me at the time. I wondered if it was some special Ruby operator, but I could find no reference to it.

After a couple of experiments I see now that it is indeed a double not operator. It serves here as a very concise way to return true or false depending on whether the variable is nil or not. Here is how it works in an irb shell:
>> foo = nil
=>> nil
>> !foo
=>> true
>> !!foo
=>> false
>> foo = 1
=>> 1
>> !foo
=>> false
>>> !!foo
=>> true

Concise is good, but not at the cost of being unclear. I'm on the fence about this one.

 

No comments:

Archive of Tips