tags:

views:

150

answers:

3
def test
!!session[:test]
end

!! - what does this do? can we remove it and still assume it will work the same?

+6  A: 

That would be the double bang (or bang bang).

It's not really an operator in itself. It is really two ! operators together...which performs double negation. It is used to make sure you're working with a boolean value.

Justin Niessner
And now I have an over-powering urge to watch _Kill Bill Vol. 1_ all over again...sigh.
David Thomas
Reminds me "I just want BANG BANG BANG" http://www.youtube.com/watch?v=vfeHkRRcdWk
Arnis L.
@David off-topic, but you invited contact in your profile however the email address you use for SO isn't public so if you want people to be able to reach you you need to include your website address or other details in your profile.
mikej
@mikej, that's a good point. Just edited an email address into it.
David Thomas
+3  A: 

The first ! coerces its operand to a boolean value, then negates it. The second ! negates the negated value. The sum effect is to coerce the operand to a boolean type. So if you change it then the method won't be returning a boolean anymore, it will be returning whatever is in the hash for that symbol. Nothing will change if you remove it, but the advantage from using !! is you can't abuse the method call to get the object from the session.

Nathan Hughes
A: 

To address your second question, your method will change subtly if you remove the double negation since you'll be returning the object instead of TrueClass or FalseClass.

The !! is generally frowned upon unless you explicitly need boolean values (for example, if you're building out an API). Since Ruby evaluates any non-nil and non-false value as truthy, it's usually safe just to return the object in question so that you can call its methods.

Raphomet