0
私はこのようなモジュールを定義した場合:モジュールは、それを含む異なるクラス間で共有されない静的プロパティをどのように定義できますか?
class A
include M
end
class B
include M
end
A.add "a"
B.add "b"
B.new.show_p
?> ["a", "b"]
の一意の静的プロパティを定義することが可能です:
module M
@@p = []
def self.included(base)
def base.add(a)
@@p += a
end
end
def show_p
@@p
end
end
を、モジュールが含まれ、すべてのクラスが同じ@@ p個の配列がありますがモジュールを含む個々の各クラスは、クラスが互いに干渉しないようにします。つまり、私はこれを行うことができます:
A.add "a"
B.add "b"
A.new.show_p
?> "a"
B.new.show_p
?> "b"
ありがとう!代わりに、静的プロパティを作成する
感謝。 'instance_variable_set 'は私が探していたものです。 –
しかし、どうすればインスタンスからアクセスできますか? f = First.new; f.class.p; この種の作品。しかし、私が最初に拡張した場合、動作しません。 –
@Peterたとえば、x.class.p。 – adamax