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

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

class Fixnum def +(other) self + other * 2 end end 

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

如何访问原始+function?

使用alias_method 。 别名Fixnum+其他东西,然后在新的+引用它:

 class Fixnum alias_method :old_add, :+ def +(other) self.old_add(other) * 2 end end 

另一个有趣的方法是将块传递给Fixnum的module_eval方法。 所以,例如:

 module FixnumExtend puts '..loading FixnumExtend module' Fixnum.module_eval do |m| alias_method :plus, :+ alias_method :min, :- alias_method :div, :/ alias_method :mult, :* alias_method :modu, :% alias_method :pow, :** def sqrt Math.sqrt(self) end end end 

现在,在我的应用程序中包含FixnumExtend后,我可以这样做:

 2.plus 2 => 4 81.sqrt => 9 

我正在使用这种方法来帮助我的OCR引擎识别手写代码。 2.div 22/2更容易。