簡體   English   中英

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

[英]How can I redefine Fixnum's + (plus) method in Ruby and keep original + functionality?

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

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

但是沒有super for + (基於其他錯誤)。

如何訪問原始+功能?

使用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更容易。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM