如何拦截对Hash类的构造函数的调用? [英] How to intercept the call to constructor of class Hash?
本文介绍了如何拦截对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.
这篇关于如何拦截对Hash类的构造函数的调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文