Bang
The three main places that the ! symbol shows up in Ruby are:
- first, as the unary not operator.
- second, in the naming of bang methods by convention.
- third, as part of the
!=operator.
Boolean Negation Operator
The unary ! operator is used to negate a condition.
!true # => false
!false # => true
Depending on how you feel about using unless, you may prefer negating a condition with !.
if !book.valid?
render :new
end
And though it's not as common in Ruby as it is in JavaScript, we can double up for a double negation.
!!nil # => false
!!false # => false
!!true # => true
!!Book.find(123) # => true or false depending on whether the book was found
Read more about that in Weird Ruby: Double Negation ↗.
Bang Methods
Methods that end in a bang (!) are often used to indicate that the method has side effects. This is a convention. There is no syntactic difference between a method defined with and without a trailing bang.
These two methods work the same:
def remove_last(items)
items.pop
end
def remove_last!(items)
items.pop
end
In fact, Array#pop is an interesting example that breaks this convention. It mutates the object it operates on, but doesn't indicate it with a !.
Not Equal Operator
The != operator is used to check if two objects are not equal. If they are not equal, it returns true, otherwise it returns false.
> 1 != 2
=> true
> {a: 1} != {a: 1}
=> false
> cs1 = CustomString.new('taco')
=> #<CustomString:0x00007fbeee83b238 @str="taco">
> cs2 = CustomString.new('taco')
=> #<CustomString:0x00007fbeebaa62f0 @str="taco">
> cs1 != cs2
=> true