我正在尝试做这样的事情:
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"
Run Code Online (Sandbox Code Playgroud)
结果[]运行良好并返回'whatever'任何键的调用(仅用于测试目的,以了解我们的改进已被有效应用)。但是,唉,initialize当我在那里实例化我的 Hash 时,任何精炼方法中的代码都不会被执行Hash.new。我是否遗漏了某些东西,或者它是否在某处initialize无法像任何其他方法一样完善?
我不确定为什么initialize不起作用。可能是因为Class#allocate以某种方式调用它绕过了细化机制?但是您可以优化new,以获得相同的效果:
module RefinedHash
refine Hash.singleton_class do
def new(*args)
obj = super
# something here
obj
end
end
end
Run Code Online (Sandbox Code Playgroud)