9

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

5 Answers 5

25

"The && and || operators are not overloadable, mainly because they provide "short circuit" evaluation that cannot be reproduced with pure method calls."

-- Jim Weirich

1
  • 4
    Actually, that's not a problem. Instead of translating a && b into a.&&(b), you could translate it into a.&& { b }. Blocks do provide lazy evaluation. Commented Oct 10, 2011 at 0:01
13

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

2
  • 1
    As Jorg mentioned in his answer, ! can be overridden. Commented Oct 9, 2011 at 21:58
  • how can I overide "+=" method? and how can I add "++" method?
    – Matrix
    Commented Apr 26, 2018 at 7:43
13

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

6

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.

2
  • how can I overide "+=" method? and how can I add "++" method?
    – Matrix
    Commented Apr 26, 2018 at 8:57
  • You can't override the += method, because, as I already explained in my answer, there is no += operator, and thus there cannot be a corresponding method. ++ is not a valid identifier, so you need to use reflection to create such a method: define_method(:'++') do |arg| puts "Hello from #{__callee__} with #{arg}" end; __send__(:'++', 42). Commented Apr 26, 2018 at 22:54
2

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

string = "test"
string << "ing"

is the same as calling:

string.<<("ing")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.