我正在尝试做这样的事情:
module RefinedHash
refine Hash do
def initialize(*args)
super
# something here
end
def [](key)
'whatever'
end
end
end
class Hello
using RefinedHash
def initialize
h = Hash.new
p h[:test]
end
end
Hello.new # => "whatever"
结果 []
运行良好,并为使用任何键的调用返回 'whatever'
(仅用于测试目的,以了解我们的优化已得到有效应用)。但是,唉,当我用上面的 Hash.new
实例化我的 Hash 时,改进的 initialize
方法中的任何代码都不会被执行。我是不是遗漏了什么,或者是否在某处声明 initialize
不能像其他任何方法一样进行细化?
最佳答案
我不确定为什么 initialize
不起作用。可能是因为 Class#allocate
以某种绕过细化机制的方式调用它?但是您可以优化 new
,以获得相同的效果:
module RefinedHash
refine Hash.singleton_class do
def new(*args)
obj = super
# something here
obj
end
end
end
关于ruby - 有什么方法可以改进 Ruby 中某些类的初始化方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54135303/