views:

811

answers:

4

Just wondering what '!!' is in ruby.

thanks!

+25  A: 

not not. It's used to convert a value to a boolean

!!nil   #=> false
!!"abc" #=> true
!!false #=> false

Its usually not necessary to use though since the only false values to ruby are nil and false, so its usually best to let that convention stand.

Think of it as

!(!some_val)

One thing that is it used for legitimately is preventing a huge chunk of data from being returned. For example you probably don't want to return 3MB of image data in your has_image? method, or you may not want to return your entire user object in the logged_in? method. Using !! converts these objects to a simple true/false.

Squeegy
So it's a double negative?
Ross
It is not a bad practise to use this. Double bang is often used in predicates ( methods ending with ? ) to return an explicitly boolean value.
Swanand
+12  A: 

It returns true if the object on the right is not nil and not false, false if it is nil or false

def logged_in?   
  !!@current_user
end
RichH
Was it obvious it came from Restful_Auth?! :D
Cameron
Not only if it's nil.
womble
+4  A: 

Note that this idiom exists in other programming languages as well. C didn't have an intrinsic bool type, so all booleans were typed as int instead, with canonical values of 0 or 1. Takes this example (parentheses added for clarity):

!(1234) == 0
!(0) == 1
!(!(1234)) == 1

The "not-not" syntax converts any non-zero integer to 1, the canonical boolean true value.

In general, though, I find it much better to put in a reasonable comparison than to use this uncommon idiom:

int x = 1234;
if (!!x); // wtf mate
if (x != 0); // obvious
Tom
Or just if (x). !! is useful when you need to get either 0/1. You may or may not consider (x) ? 1 : 0 clearer.
derobert
+6  A: 

! means negate boolean state, two !'s is nothing special, other than a double negation.

!true == false
# => true

It is commonly used to force a method to return a boolean. It will detect any kind of truthiness, such as string, integers and what not, and turn it into a boolean.

!"wtf"
# => false

!!"wtf"
# => true

A more real use case:

def title
  "I return a string."
end

def title_exists?
  !!title
end

This is useful when you want to make sure that a boolean is returned. IMHO it's kind of pointless, though, seeing that both "if 'some string'" and "if true" is the exact same flow, but some people find it useful to explicitly return a boolean.

August Lilleaas
it seems to me like just a faster way than using an if statement or a ternary operator. Since you can't just return `title`, may as well do the closest thing to it... I suppose
Carson Myers