Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we override `||` and `&&`?

Tags:

ruby

keyword

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 &&?

like image 612
Arup Rakshit Avatar asked Mar 09 '13 13:03

Arup Rakshit


1 Answers

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.

like image 71
Linuxios Avatar answered Nov 17 '22 22:11

Linuxios