1

Possible Duplicate:
What does !! mean in ruby?

I'm learning ruby/rails and found a tutorial with the following code example:

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

I don't have any idea for what the !! do, neither the !!self do.

I really googled about that, but doesn't find anything.

Can anyone give a short explanation? Thanks in advance.

Community
  • 1
  • 1
caarlos0
  • 20,020
  • 27
  • 85
  • 160

3 Answers3

3

It's the "not" operator (!) repeated twice, so that it's argument will be coerced to its negated boolean and then its corresponding boolean. Basically, it's a way to coerce any object into its boolean value.

!!false # => false
!!nil # => false
!!true # => true
!!{} # => true
!![] # => true
!!1 # => true
!!0 # => true (Surprised? Only 'false' and 'nil' are false in Ruby!)
maerics
  • 151,642
  • 46
  • 269
  • 291
2

It's usually employed to force-cast an arbitrary value into one of true or false. This is often useful for converting between arbitrary numbers, strings, or potential nil values.

In your example this is extremely inefficient since an entire model is loaded only to be discarded. It would be better written as:

def role?(role)
  self.roles.count_by_name(role.to_s.camelize) > 0
end

That query will return a singular value that is used for comparison purposes, the result of which is automatically a boolean.

tadman
  • 208,517
  • 23
  • 234
  • 262
0

This confirms that the operation will always return the boolena value

!!1 #gives you true
!!nil #gives you false 

In ruby nil, false is consider as false and 0, 0.0 and other objects are consider as true

Salil
  • 46,566
  • 21
  • 122
  • 156