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.
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.