如何在继承Ruby散列时重写[] =方法? [英] How can I override the []= method when subclassing a Ruby hash?

查看:108
本文介绍了如何在继承Ruby散列时重写[] =方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



什么是正确的语法来覆盖 [key] = 语法方法来完成这个任务?我想插入我的代码,然后调用父级方法。

这对C方法可能吗?我从文档中看到,底层方法是

$ $ p $ rb_hash_aset(VALUE hash,VALUE key,VALUE val)

这是如何分配到括号语法的?

解决方案

方法签名是 def [] =(key,val),并且 super 调用父方法。下面是一个完整的例子:

  class MyHash<哈希
def [] =(key,val)
printf(key:%s,val:%s\,key,val)
super(key,val)
end
end

x = MyHash.new

x ['a'] ='hello'
x ['b'] ='world '

px


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?

解决方案

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

这篇关于如何在继承Ruby散列时重写[] =方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆