我的问题是:如何在内置类(例如 Integer.new.+)上重载运算符,但仅限于某些情况,具体取决于第二个操作数的类
这是我正在寻找的行为:
myObject = myClass.new
1 + myObject #=> special behaviour
1 + 2 #=> default behaviour (3)
Run Code Online (Sandbox Code Playgroud)
例如,在 Python 中,我会__radd__在 myClass 上定义一个方法来覆盖情况 1。
我尝试过使用super但显然Numeric没有操作员方法。
理想情况下,我正在寻找一种提取+方法并重命名它的方法。
像这样:
class Integer
self.plus = self.+ # you know what i mean, I don't know how else to express this.
# I also know that methods don't work like this, this is just to
# illustrate a point.
def + other
other.class == myClass ? …Run Code Online (Sandbox Code Playgroud)