Reputation: 1344
I want to define a custom :+= method on my Ruby class that modifies the instance. However, the following code raises syntax error, unexpected '=', expecting ';' or '\n'
def +=(other)
@value += other.to_f
end
What are my options here? I see that Fixnum
has :+@
and :-@
methods, but I don't exactly see what they do in the documentation. Are those the methods I want to write?
Upvotes: 0
Views: 157
Reputation: 211540
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
Upvotes: 5
Reputation: 22926
I am not really sure, but you do not need the = operator.
def +(other)
@value += other.to_f
end
Example from here:
class Money
attr_accessor :value
def +(b)
result = dup
result.value += b.value
return result
end
def -(b)
result = dup
result.value += b.value
return result
end
end
Upvotes: 1