开发者

What does !!some_object do? [duplicate]

开发者 https://www.devze.com 2023-01-29 08:25 出处:网络
This question already has answers here: Closed 12 years ago. Possible D开发者_运维知识库uplicate:
This question already has answers here: Closed 12 years ago.

Possible D开发者_运维知识库uplicate:

What does !! mean in ruby?

what is this function doing?

def current_product?
   !!current_product
end

Isn't that a double negative?


!! is basically a cast to boolean. If current_product is truthy, !current_product is false and !!current_product is true, and vice versa. I.e. it converts truthy values to true and falsy values to false.


It's effectively a cast/conversion to boolean.

Similar question, but for C++: Doube Negation in C++ code

Also a pretty decent post about it here: !! (The double bang / double not) in Ruby


This is a pattern you'll see in any language where every object has a truth value, but there are canonical booleans (whether they be called True and False, 1 and 0, 1 and "", t and nil, whatever). !!x is essentially a "cast to boolean", in that !!x has the same truth-value as x, but !!x will always be one of the canonical true/false values, instead of any old true/false value.

0

精彩评论

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