11

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?

3
  • For the culture, note that the !! operator is usually called "double bang operator". Sep 26, 2011 at 21:35
  • Also note that return and self. are both redundant here. Sep 26, 2011 at 21:38
  • @Kernald - hmm, there is no !! operator.
    – steenslag
    Sep 26, 2011 at 21:38

5 Answers 5

18

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.

0
7

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.

0
5

This is a double negation which results in a boolean:

irb(main):016:0> !1
=> false
irb(main):013:0> !0
=> false
irb(main):014:0> !nil
=> true
irb(main):015:0> !!nil
=> false
0

Yes in your case you can be sure that the function is returning only true or false. If you would omit !! you would return a list of roles

0

with this little trick you get the actual boolean value of an expression, e.g.:

!! 3 
=> true

!! nil
 => false 

!! 0
 => true 

In Ruby anything that isn't nil or false , is true!

In your example code this trick makes sure that you never return anything else
but true or false

If you would omit the !! , you would return the list of roles, or nil

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.