Ruby:仅在某些情况下重载运算符行为

Aso*_*hid 4 ruby methods operator-overloading operator-keyword

我的问题是:如何在内置类(例如 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 ? special behaviour : self.plus other
  end
end
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助

Ale*_*kin 6

到目前为止,这里发布的两种方法都是传统的 Rails 方法,这是完全错误的。它依赖于这样一个事实:该类没有调用的方法plus ,并且没有人会重新打开该类来创建名为 的方法plus。否则事情就会变得疯狂。

正确的解决方案是Module#prepend

Integer.prepend(Module.new do
  def + other
    case other
    when Fixnum then special_behaviour
    else super(other)
    end
  end
end)
Run Code Online (Sandbox Code Playgroud)