2012-10-20 52 views
3

我有一個擴展哈希類,我想跟蹤何時修改哈希鍵。如何在子類化Ruby散列時重寫[] =方法?

什麼是正確的語法來覆蓋[key]=語法的方法來完成這個?我想插入我的代碼,然後調用父方法。

這是可能的C方法?我從文檔中看到,底層方法是

rb_hash_aset(VALUE hash, VALUE key, VALUE val) 

這是如何分配到括號語法?

回答

5

方法簽名爲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 
+1

[key] =值表示法被稱爲「語法糖」 –

+0

我意識到這一點。目前尚不清楚這種語法糖如何被分配到底層方法。 – fields

+0

** http://ruby.dbgr.cc/e**如果您想要瀏覽/調試代碼 –

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

好吧,也許這應該是很明顯。 – fields

2

我認爲使用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