9

您可以使用

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)

4

2 回答 2

16

这段代码将起作用:

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定义一个实例方法。

于 2015-12-07T20:32:04.583 回答
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

请注意副作用。

于 2015-08-20T10:14:39.667 回答