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

不打扰是莪最后的温柔 提交于 2019-12-23 22:42:10

问题


I have a class that extends Hash, and I want to track when a hash key is modified.

What's the right syntax to override the [key]= syntactic method to accomplish this? I want to insert my code, then call the parent method.

Is this possible with the C methods? I see from the docs that the underlying method is

rb_hash_aset(VALUE hash, VALUE key, VALUE val)

How does that get assigned to the bracket syntax?


回答1:


The method signature is def []=(key, val), and super to call the parent method. Here's a full example:

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



回答2:


I think using set_trace_func is more general solution

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



回答3:


class MyHash < Hash
  def []=(key,value)
    super
  end
end


来源:https://stackoverflow.com/questions/12989011/how-can-i-override-the-method-when-subclassing-a-ruby-hash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!