您可以使用
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)
发布于 2015-12-07 20:32:04
这段代码将起作用:
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
发布于 2015-08-20 10:14:39
精化只修改类,而不是模块,因此参数必须是类。
- 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请注意副作用。
https://stackoverflow.com/questions/32115323
复制相似问题