Ruby重载+运算符

Rav*_*ous 2 ruby operator-overloading

在ruby中重载运算符的正确方法是什么?我需要做些什么来重新定义+如何工作?使用+运算符时不调用此函数.

def +(a,b)
 return a * b
end

p 2 + 2 
Run Code Online (Sandbox Code Playgroud)

Cth*_*lhu 5

重载运算符是根据第一个操作数的类来解析的,所以如果你想重载简单整数的加法,那么这样的东西应该可以工作:

class Fixnum
  def +(other)
    return self * other
  end
end
Run Code Online (Sandbox Code Playgroud)

我不建议你真的这样做,顺便说一下.