In message "Reversing receiver and argument for commutative math operations"
on 02/05/10, "Gray, Jeff" <jeff.gray / intel.com> writes:
|Let's say I have a class that overrides certain arithmetic operators like +
|and *, so that
|
| obj = MyClass.new(5, "some other attribute")
| this_obj = obj * 2 # this_obj == MyClass.new(10)
| that_obj = 2 * obj # that_obj == this_obj is desired
|Is there a way to do what I'd like?
How about
class MyClass
def initialize(v)
@value = v
end
def value
@value
end
def *(x)
if x.type <= self.type
x = x.value
end
self.type.new(self.value * x)
end
def coerce(x)
[self.type.new(x), self]
end
end
p MyClass.new(1) * 2
p 2 * MyClass.new(2)
matz.