David A. Black stated in his book:
[T]he conditional assignment operator
||=
, as well as its rarely spotted cousin &&=, both of which provide the same kind of shortcut as the pseudooperator methods but are based on operators, namely||
and&&
, which you can’t override.
Why did he specifically mention that we can't override ||
and &&
?
Unlike some other operators on objects, who's behavior logically can depend on class, the boolean operators are part of the language. When you have an operator like, say, ==
, it is logical to say that the behavior of this operator depends on the type of object. A string should check character by character, a Hash key-value tuple by key-value tuple, etc. However, the behavior of &&
and ||
are based on the language's definition of true and false, not anything object specific. If the language allowed you to override these operators, there could be no consistent boolean model, and these operators would become completely useless.
Additionally, there is a performance consideration too. Because &&
and ||
are short circut operators, which means that if the first argument to, say, &&
, evaluates to false, the second one is never even evaluated. With ||
, if the first evaluates to true, the second is never evaluated. This behavior would not be possible if you could override these operators, as in Ruby operators are overloaded as methods. And all parameters must be evaluated, by definition, before the method is called. So, the performance boost, and programming convenience of a short circuit operator is lost.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With