如何在Ruby中重新定义Fixnum的+(plus)方法并保留原始+功能?

kar*_*dog 7 ruby rubinius yarv super

这引发了我在1.9.2 Ruby中的SystemStackError(但在Rubinius中工作):

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

但没有super+(基于其他错误).

我如何访问原始+功能?

Fra*_*ser 14

使用alias_method.别名Fixnum+别的东西,然后参考它在新的+:

class Fixnum
  alias_method :old_add, :+
  def +(other)
    self.old_add(other) * 2
  end
end
Run Code Online (Sandbox Code Playgroud)

  • @Andrew:听到*覆盖整个加法*对于IRb而言并不太好,我并不感到惊讶......这是一个非常糟糕的黑客,我几乎无法用语言描述它. (3认同)