Is there a way to override a class’s operator, by creating a new operator method inside a module, then mixing that module into the class?
eg, this overrides Fixnum’s + operator:
class Fixnum
def +(x)
product = x
product = product * self
return product
end
end
p 3 + 3
# => 9
This does not override Fixnum’s + operator:
module NewOperators
def +(x)
product = x
product = product * self
return product
end
end
class Fixnum
include NewOperators
end
p 3 + 3
# => 6
Your question led me to this interesting article which describes the problem:
Fixing Ruby’s Inheritance Model with Metamorph
And his solution is to transparently define all new methods inside an anonymous inner module:
This is also conveniently packaged in a library called metamorph, which allows you to have mixin methods override class methods by just requiring it.