如何拦截对Hash类的构造函数的调用?
问题描述:
我想在调用 Hash 类的构造函数或初始化 Hash 对象时执行函数.我已经使用
I want to execute a function when a constructor of class Hash is called or when a Hash object is initialized. I have implemented my objective using
class Hash
def initialize
p "Constructor call"
end
end
当 Hash 对象按如下方式初始化时,上面的代码可以正常工作:
The code above works fine when a Hash object is initialized as follows:
a = Hash.new(:a1 => "Hi")
但是,当我使用以下代码时:
However, when I use the following code:
a = {:a1 => "Hi"}
然后,它失败或未调用构造函数.那么,如何拦截第二个代码片段中的调用?
Then, it fails or the constructor is not called. So, how to intercept the call made in the second code snippet?
提前致谢.
答
恐怕你不能在 MRI 中,但可能可以在 Rubinius/JRuby 中管理一些东西.
I'm afraid you can't in MRI, but could probably manage something in Rubinius / JRuby.