如何在Ruby中优化模块方法?

菲利普·巴图兹(Filip Bartuzi)

您可以使用

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章