您可以使用
优化您的类(class)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:错误的参数类型模块(预期类)
最佳答案
这段代码可以工作:
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 上定义实例方法。
关于ruby - 如何改进 Ruby 中的模块方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32115323/