What is it "!!" does character mean in Ruby?

def test !!session[:test] end 

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

+4
ruby
Sep 29 '10 at 12:09 on
source share
3 answers

This will be a double bang (or bang bang) .

This is not a real operator in itself. These are really two operators ! together ... which performs double negation. It is used to make sure that you are working with a boolean.

+9
Sep 29 '10 at 12:13
source share

First one ! forces its operand to a boolean value and then cancels it. Second one ! negates a negative value. The total effect is to force the operand to a Boolean type. Therefore, if you change it, then the method will no longer return a boolean value, it will return everything that is in the hash for this symbol. Nothing will change if you delete it, but the advantage of using it !! is that you cannot abuse a method call to get an object from a session.

+4
Sep 29 '10 at 12:49 on
source share

To answer the second question, your method will change subtly if you remove the double negation, since you will return an object instead of TrueClass or FalseClass.

The !! usually disapproving if you clearly don't need boolean values ​​(for example, if you are creating an API) Since Ruby evaluates any non-nil and non-false values ​​as true, it is usually safe to simply return the object in question so that you can call its methods.

0
Sep 29 '10 at 17:22
source share



All Articles