views:

1929

answers:

5

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
+7  A: 

Methods are overloadable, those are part of the language syntax.

Farrel
+7  A: 

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).

Jordi Bunster
+1  A: 

And let's not forget about << for example:

string = "test"
string << "ing"

is the same as calling:

string.<<("ing")
Ryan Bigg
+1  A: 

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.

Jörg W Mittag