two bangs
The !
or bang operator is common in across languages as a ‘not’ operator. Aka, it returns the opposite of the operand.
Here are some examples in Ruby:
!true
# false
!8
# false
!Array
# false
!nil
# true
The !!
or double-bang takes the negated result and negates it again. It is effectively taking any type (such as a number, string, or object) and casting it to a boolean.
!!true
# true
!!8
# true
!!Array
# true
!!nil
# false
This is useful in any situation where you need to ensure a boolean type, for example, instead of a nil
value.