如果我定义这样的模块:
module M
@@p = []
def self.included( base )
def base.add( a )
@@p += a
end
end
def show_p
@@p
end
end
然后包含该模块的每个类都将具有相同的@@ p数组:
class A
include M
end
class B
include M
end
A.add "a"
B.add "b"
B.new.show_p
?> ["a", "b"]
是否可以为包含该模块的每个单独的类定义一个唯一的静态属性,因此这些类不会相互干扰?即所以我可以这样做:
A.add "a"
B.add "b"
A.new.show_p
?> "a"
B.new.show_p
?> "b"
谢谢!
答案 0 :(得分:0)
不是创建静态属性,而是在类对象本身上定义一个属性:
module Foo
def self.included(base)
base.instance_variable_set(:@p, [])
class << base
attr_reader :p
def add(a)
@p << a
end
end
end
end
class First
include Foo
end
class Second
include Foo
end
require 'pp'
First.add "a"
Second.add "b"
pp First.p
pp Second.p
输出:
["a"] ["b"]