What is the purpose of the exclamation mark right before the taking_damage
method in this example of code?
if warrior.health < 20 && !taking_damage?(warrior)
warrior.rest!
end
What is the purpose of the exclamation mark right before the taking_damage
method in this example of code?
if warrior.health < 20 && !taking_damage?(warrior)
warrior.rest!
end
It is the boolean operation Negation and thus equivalent to the Ruby keyword not
.
You can read the line like this:
“If the warrior's health is below 20 and the warrior is NOT taking damage then the warrior must rest.”</p>
It is the negation operator which takes the method/variable's truthiness and returns the opposite of it.
此运算符还可用于将任何值转换为真假(布尔值)。这是一个例子:
> !nil
=> true
> !!nil
=> false