howto let ruby share data beetwen a class and its subclasses in conjuction with extend

假装没事ソ 提交于 2019-12-24 20:19:27

问题


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

this produces

42
nil

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?


回答1:


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

this produces

42
42
23

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




回答2:


B::A.f will produce the correct result




回答3:


Class variables may do what you need here:

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

This produces:

42
42

This seems to be closer to the behavior you want:

def M()
  m = Module.new
  m.module_eval <<-HERE
    def f=(x)
      @@f= x
    end

    def f
      @@f
    end
  HERE
  m
end

class A
  extend M()
end

class B < A
end

class C
  extend M()
end


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

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

Produces:

 42
 42
 23
 42
 42


来源:https://stackoverflow.com/questions/1451143/howto-let-ruby-share-data-beetwen-a-class-and-its-subclasses-in-conjuction-with

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