Double Exclmations !! In Ruby

Today I hit this in a Ruby example online:

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

Note the double exclamation (!!). This converts the value to boolean.

!! is just ! (the boolean negation operator) written twice. It will negate the argument, then negate the negation. It’s useful because you can use it to get a boolean from any value. The first ! will convert the argument to a boolean, e.g. true if it’s nil or false, and false otherwise. The second will negate that again so that you get the boolean value of the argument, false for nil or false, true for just about everything else.

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)

Jason Meridth

jmeridth

My name is Jason Meridth. I am a continuously learning senior software developer/devops/team lead/development manager trying to not let best be the enemy of better. I reserve the right to change my mind upon obtaining more information. I am also the owner and principal software consultant at Meridth, LLC. If you have any software, hardward, networking, process, etc needs please don't hesitate to reach out to me.

Raspberry Pi Kubernetes Cluster - Part 2

Howdy again.Alright, my 8 port switch showed up so I was able to connect my raspberry 3B+ boards to my home network. I plugged it in wit...… Continue reading

Raspberry Pi Kubernetes Cluster - Part 1

Published on April 07, 2018

SSH - Too Many Authentication Failures

Published on March 28, 2018