gpt4 book ai didi

ruby - 如何改进 Ruby 中的模块方法?

转载 作者:数据小太阳 更新时间:2023-10-29 06:52:37 24 4
gpt4 key购买 nike

您可以使用

优化您的类(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

说明:

定义一个模块#methodequivalent在其 #singleton_class 上定义实例方法。

关于ruby - 如何改进 Ruby 中的模块方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32115323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com