在子类化Ruby哈希时如何覆盖 =方法?
我有一个扩展Hash的类,我想跟踪修改哈希键的时间。
什么是覆盖[key]=
语法方法来实现此目的的正确语法? 我想插入我的代码,然后调用父方法。
这可能与C方法有关吗? 我从文档中看到底层方法是
rb_hash_aset(VALUE hash, VALUE key, VALUE val)
如何将其分配给括号语法?
方法签名是def []=(key, val)
,而super
是调用父方法。 这是一个完整的例子:
class MyHash < Hash def []=(key,val) printf("key: %s, val: %s\n", key, val) super(key,val) end end x = MyHash.new x['a'] = 'hello' x['b'] = 'world' px
我认为使用set_trace_func
是更通用的解决方案
class MyHash < Hash def initialize super end def []=(key,val) super end end set_trace_func proc { |event, file, line, id, binding, classname| printf "%10s %8s\n", id, classname if classname == MyHash } h = MyHash.new h[:t] = 't' #=> initialize MyHash initialize MyHash initialize MyHash []= MyHash []= MyHash []= MyHash
class MyHash < Hash def []=(key,value) super end end