开发者

What does the "!!" symbol mean in Ruby?

def test
!!session[:test]
end

!! - what does th开发者_StackOverflow社区is do? can we remove it and still assume it will work the same?


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜