Unlike C++ or other languages with robust overrides, there's no such method as +=
in Ruby.
What's happening internally is a sort of expansion. For example:
x += n
If x
is a variable, then this is equivalent to:
x = x.send(:+, n)
If x=
is defined, then this is equivalent to:
send(:x=, x.send(:+, n))
Whatever you need to do to override must be to redefine x=
or +
on the class of x
.
Remember that the +
method should not modify x
. It's supposed to return a copy of x
with the modification applied. It should also return an object of the same class of x
for consistency.
Your method should look like:
def +(other)
# Create a new object that's identical in class, passing in any arguments
# to the constructor to facilitate this.
result = self.class.new(...)
result.value += other.to+f
result
end