Why would you use a !! operator
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开发者_Go百科 as
return self.roles.find_by_name(role.to_s.camelize)
Does adding the double exclamation mark add something to the evaluation?
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.
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.
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
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
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
精彩评论