如何在Ruby中改进模块方法?

时间:2015-08-20 10:05:25

标签: ruby ruby-2.0 ruby-2.1 ruby-2.2

您可以使用

优化您的课程
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)

2 个答案:

答案 0 :(得分:13)

这段代码将起作用:

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 equivalent,以便在 #singleton_class 上定义实例方法。

答案 1 :(得分:1)

  

优化只修改类,而不修改模块,因此参数必须是类。

- 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

请注意副作用。

相关问题