Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use a !! operator

Tags:

operators

ruby

I came across abit of ruby in a example

def role?(role)
  return !!self.roles.find_by_name(role.to_s.camelize)
end

Why would you ever use !!? Is it not the same as

 return self.roles.find_by_name(role.to_s.camelize)

Does adding the double exclamation mark add something to the evaluation?

like image 523
Benjamin Udink ten Cate Avatar asked Sep 26 '11 21:09

Benjamin Udink ten Cate


People also ask

Why do we need operators in C?

C operators are one of the features in C which has symbols that can be used to perform mathematical, relational, bitwise, conditional, or logical manipulations. The C programming language has a lot of built-in operators to perform various tasks as per the need of the program.

What is the * operator and what does it do?

* operator and what does it do? It is the same as the class member access operator, or arrow operator (->) , which allows you to access a member of an object through a pointer to the object.

Why is operator important in programming?

An operator in a programming language is a symbol that tells the compiler or interpreter to perform specific mathematical, relational or logical operation and produce final result.

Why do we need a operator in Java?

Operators are special symbols that perform specific operations on one, two, or three operands, and then return a result. As we explore the operators of the Java programming language, it may be helpful for you to know ahead of time which operators have the highest precedence.


2 Answers

You use it if you only want the boolean, not the object. Any non-nil object except for boolean false represents true, however, you'd return the data as well. By double negating it, you return a proper boolean.

like image 166
Femaref Avatar answered Oct 11 '22 12:10

Femaref


Disclaimer: Not a ruby programmer but having a stab at this.

!!, double bang or "not not", might convert the value to a boolean. One ! returns the boolean opposite and another bang thereafter will flip it to its normal boolean value.

like image 21
Lewis Norton Avatar answered Oct 11 '22 14:10

Lewis Norton