如何让ruby共享数据,从而扩展一个类及其子类 [英] howto let ruby share data beetwen a class and its subclasses in conjuction with extend

查看:82
本文介绍了如何让ruby共享数据,从而扩展一个类及其子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

module M

  def f=(x)
    @f= x
  end

  def f
    @f
  end

end

class A
  extend M
end

class B < A
end

A.f= 42
puts A.f
puts B.f

这产生

42
nil

@f是A和B的类变量吗? 如何仅通过将其写入M来在A和B之间共享变量?

Is @f a class variable to A and B? How do I share a variable between A and B by only writing this into M?

推荐答案

通过不直接使用@@ f,而是使用class_variable_set()和class_variable_get(),可以在M内部使用A,B和C的类变量.

By not using @@f directly, but rather class_variable_set() and class_variable_get(), class variables of A, B and C can be used from within M.

module M

    def f=(x)
        class_variable_set("@@f", x)
    end

    def f
        class_variable_get("@@f")
    end

end

class A
    extend M
end

class B < A
end

class C
    extend M
end

A.f= 42
C.f= 23
puts A.f
puts B.f
puts C.f

这产生

42
42
23

如您所见,变量是由A和B共享的,而不是C共享的.

As you can see, the variables are shared by A and B, but not C.

这篇关于如何让ruby共享数据,从而扩展一个类及其子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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