我想跟踪一个类的所有实例,下面的代码运行良好,但不是很干。
class BaseClass
end
class ClassA < BaseClass
@@instances = []
attr_accessor :name
def initialize(name)
@name = name
@@instances << self
end
def self.list
@@instances
end
def to_s
@name
end
end
class ClassB < BaseClass
@@instances = []
attr_accessor :name
def initialize(name)
@name = name
@@instances << self
end
def self.list
@@instances
end
def to_s
@name
end
end
puts "Creating instances"
a = ClassA.new "a"
aa = ClassA.new "aa"
b = ClassB.new "b"
puts "Listing for ClassA"
puts ClassA.list
puts "Listing for ClassB"
puts ClassB.list
其输出变为
Creating instances
Listing for ClassA
a
aa
Listing for ClassB
b
完美的。但是,当我尝试像这样对其进行重复数据删除时
class BaseClass
@@instances = []
attr_accessor :name
def initialize(name)
@name = name
@@instances << self
end
def self.list
@@instances
end
def to_s
@name
end
end
class ClassA < BaseClass
end
class ClassB < BaseClass
end
puts "Creating instances"
a = ClassA.new "a"
aa = ClassA.new "aa"
b = ClassB.new "b"
puts "Listing for ClassA"
puts ClassA.list
puts "Listing for ClassB"
puts ClassB.list
我得到以下输出
Creating instances
Listing for ClassA
a
aa
b
Listing for ClassB
a
aa
b
这是有道理的,因为@@instances
在中定义BaseClass
并与ClassA
和共享ClassB
。
我怎样才能让我的代码去重看起来像后一个例子,这样它的行为就像前一个例子?