簡體   English   中英

如何在Ruby中優化模塊方法?

[英]How to refine module method in Ruby?

你可以改進你的課程

module RefinedString
  refine String do
    def to_boolean(text)
    !!(text =~ /^(true|t|yes|y|1)$/i)
    end
  end
end

但如何細化模塊方法? 這個:

module RefinedMath
  refine Math do
    def PI
      22/7
    end
  end
end

引發: TypeError: wrong argument type Module (expected Class)

這段代碼將起作用:

module Math
  def self.pi
    puts 'original method'
   end
end

module RefinementsInside
  refine Math.singleton_class do
    def pi
      puts 'refined method'
    end
  end
end

module Main
  using RefinementsInside
  Math.pi #=> refined method
end

Math.pi #=> original method

說明:

定義模塊#method等效於在其#singleton_class限定實例方法。

優化只修改類,而不修改模塊,因此參數必須是類。

- http://ruby-doc.org/core-2.1.1/doc/syntax/refinements_rdoc.html

一旦您意識到自己在做什么,就有兩種方法可以全局優化模塊方法。 由於ruby具有開放類,您可以簡單地覆蓋該方法:

▶ Math.exp 2
#⇒ 7.38905609893065
▶ module Math
▷   def self.exp arg
▷     Math::E ** arg
▷   end  
▷ end  
#⇒ :exp
▶ Math.exp 2
#⇒ 7.3890560989306495

是否要保存要覆蓋的方法的功能:

▶ module Math
▷   class << self
▷     alias_method :_____exp, :exp  
▷     def exp arg  
▷       _____exp arg    
▷     end  
▷   end  
▷ end  
#⇒ Math
▶ Math.exp 2
#⇒ 7.3890560989306495

請注意副作用。

暫無
暫無

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

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