Can anybody tell me why a lot of Ruby boolean methods use this double negation convention?
!!(boolean expression)
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The double negation ensures that no matter the initial value, you will always get
trueorfalse, never some mystery value.This is handy because it avoids dangling references to objects you no longer require, or having to differentiate between two types of false value,
nilandfalse.Often you will see methods written like this:
This will return
trueorfalseand that value can be used for whatever purpose is required. Compare that with this:In this case if you save the value, you’re actually saving the whole
@session_userobject, which could be a fairly significant chunk of memory. This memory cannot be released until your reference to it falls out of scope. Since there is only onetrueand onefalse, there’s no need for garbage collection.