Why Does Ruby Only Permit Certain Operator Overloading
-
01-07-2019 - |
Question
In Ruby, like in many other OO programming languages, operators are overloadable. However, only certain character operators can be overloaded.
This list may be incomplete but, here are some of the operators that cannot be overloaded:
!, not, &&, and, ||, or
Solution
Methods are overloadable, those are part of the language syntax.
OTHER TIPS
Yep. Operators are not overloadable. Only methods.
Some operators are not really. They're sugar for methods. So 5 + 5
is really 5.+(5)
, and foo[bar] = baz
is really foo.[]=(bar, baz)
.
In Ruby 1.9, the !
operator is actually also a method and can be overriden. This only leaves &&
and ||
and their low-precedence counterparts and
and or
.
There's also some other "combined operators" that cannot be overriden, e.g. a != b
is actually !(a == b)
and a += b
is actually a = a+b
.
And let's not forget about <<
for example:
string = "test"
string << "ing"
is the same as calling:
string.<<("ing")