4
def test
!!session[:test]
end

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

Kristopher Johnson
  • 81,409
  • 55
  • 245
  • 302
Dhanu
  • 69
  • 7

3 Answers3

9

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
  • 242,243
  • 40
  • 408
  • 536
  • And now I have an over-powering urge to watch _Kill Bill Vol. 1_ all over again...sigh. – David Thomas Sep 29 '10 at 12:17
  • 1
    Reminds me "I just want BANG BANG BANG" http://www.youtube.com/watch?v=vfeHkRRcdWk – Arnis Lapsa Sep 29 '10 at 12:21
  • @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 Sep 29 '10 at 12:50
  • @mikej, that's a good point. Just edited an email address into it. – David Thomas Sep 29 '10 at 13:07
4

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
  • 94,330
  • 19
  • 181
  • 276
0

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
  • 3,589
  • 1
  • 23
  • 12