Ruby overloading

A new thing on my quest to learn the new language is weird inconsistency that bugged me lately: In Ruby you can overload virtually everything. That is, everything except the “equals” operator.

In spite of this, half of the Rubyists seem to believe that they overload the “equals” sign all the time.

Still, if you have this kind of expression:

variable_1 = variable_2

it will assign the value of variable_2 to variable_1, and there’s no way to change this behaviour.

However, if have something that looks like this

object.method = expression

the code will actually be evaluated equivalent to

object.send(“method=”, expression)

Yes, that’s true: The expression above will actually call a method called “method=” with the value left of the “equals” sign as a parameter.

The nice point is that you can at least write a logic for “method assignments”.

Not so nice is the fact that there’s still no way to overload “equals”, and that these method assignments work completely different than “normal” operator overloading.

Which means that if you call

object.method + expression

Ruby will first evaluate object.method and then call the “+” method on the object that was returned from the first call.

On the other hand, the call

object.method = expression

will call the “method=” method on object and return it’s result. And “method=” is completely unrelated to “method”.

Even worse, if you call

object.method += expression

this will evaluate “object.method”, then call the “+” method on the object that was returned by this call. Then it will call “method=”, giving the reference to the object from the previous step as a parameter:

x = object.method


Comments are closed.

Blog at

Up ↑

%d bloggers like this: