我想跟踪一个类的所有实例,以下代码完美无缺,但不是很干。
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
共享。
如何让我的代码重复数据删除看起来像后一个例子,这样它的行为就像前一个例子一样?
答案 0 :(得分:0)
最简单的方法是摆脱你想要做的伎俩,然后使用ObjectSpace.each_object
。
class BaseClass
attr_accessor :name
def initialize(name); @name = name 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 ObjectSpace.each_object(ClassA).to_a
puts "Listing for ClassB"
puts ObjectSpace.each_object(ClassB).to_a
这给出了
Creating instances
Listing for ClassA
aa
a
Listing for ClassB
b