Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, !! operator (a/k/a the double-bang) [duplicate]

Tags:

operators

ruby

Possible Duplicate:
What does !! mean in ruby?

Hi,

I'm new to Ruby and can't find anywhere description of what "!!" means.

Here's an example:

def signed_in?   !!current_user end 

If this is a double negative, why not to say:

def signed_in?   current_user end 

Please help.

like image 257
Vitaly Avatar asked Oct 22 '10 05:10

Vitaly


People also ask

What does the bang operator do in Ruby?

The bang operator is a method that is used to return boolean values. What does that mean though? We should consider the concepts of truthiness and falseness in Ruby. In Ruby everything except nil and false are considered truthy values.

What is double bang operator?

AndroidMobile DevelopmentApps/ApplicationsKotlin. In Kotlin, "!!" is an operator that is known as the double-bang operator. This operator is also known as "not-null assertion operator". This operator is used to convert any value to a non-NULL type value and it throws an exception if the corresponding value is NULL.

How does && work Ruby?

How about the && operator? The fact that && has higher precedence than the assignment operator (=), makes it so that the arguments to the AND function are true , and false . The ones in the inner parenthesis. And because of the short-circuit evaluation, the first value is returned.


1 Answers

In Ruby (and many other languages) there are many values that evaluate to true in a boolean context, and a handful that will evaluate to false. In Ruby, the only two things that evaluate to false are false (itself) and nil.

If you negate something, that forces a boolean context. Of course, it also negates it. If you double-negate it, it forces the boolean context, but returns the proper boolean value.

For example:

"hello"   #-> this is a string; it is not in a boolean context !"hello"  #-> this is a string that is forced into a boolean            #   context (true), and then negated (false) !!"hello" #-> this is a string that is forced into a boolean            #   context (true), and then negated (false), and then            #   negated again (true) !!nil     #-> this is a false-y value that is forced into a boolean            #   context (false), and then negated (true), and then            #   negated again (false) 

In your example, the signed_in? method should return a boolean value (as indicated by convention by the ? character). The internal logic it uses to decide this value is by checking to see if the current_user variable is set. If it is set, it will evaluate to true in a boolean context. If not, it will evaluate as false. The double negation forces the return value to be a boolean.

like image 58
pkaeding Avatar answered Oct 09 '22 20:10

pkaeding