繁体   English   中英

在子类化Ruby哈希时如何覆盖[] =方法?

[英]How can I override the []= method when subclassing a Ruby hash?

我有一个扩展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'

p x

我认为使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM