-1

I have an ADT (Abstract Data Type) and for that I wrote a method +(other). +(other) returns a new ADT.

If I use it like:

adt += otherAdt

It will be overwrite adt.

But now I want to write a method with name +=(other) to change adt instead of create a new one.

I try to name my method +=(other) and get an error.

My alternative is to name it plus=(other).

I know that if I have two arrays aArr and bArr and write:

aArr += bArr

That aArr is a new array with the elements of aArr and bArr and thus has a new Object-ID.

So, is there a way to overwrite +=, -=, *= and *= in Ruby? And if so, how would it look like?

Edit: I asked a question below @Mladen Jablanović's answer.

1 Answers1

0

You can not. a += b is a shorthand for a = a + b and it always assigns back to a, and you can't redefine assignment, because it is not a method.

Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113