0

我想跟踪一个类的所有实例,下面的代码运行良好,但不是很干。

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

我怎样才能让我的代码去重看起来像后一个例子,这样它的行为就像前一个例子?

4

1 回答 1

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
于 2013-07-20T09:43:18.950 回答