在创建时收集数组中的类实例

时间:2013-06-25 04:14:46

标签: ruby

class Person
  attr_accessor :name

  def initialize(name)
     @@name = name
     people.push($)
  end
end

它不必在初始化函数中。我只想要创建所有人员的数组。

p1 = Person.new("joe")
p2 = Person.new("rick")
people.inspect #-->would return [p1, p2]

3 个答案:

答案 0 :(得分:4)

如果您只想要Person的所有实例的列表,则无需在创建时添加它们。只需通过以下方式访问它们:

ObjectSpace.each_object(Person).to_a

答案 1 :(得分:2)

@ sawa的答案是最好的,因为它不会阻止垃圾收集。如果您确实想要在创建每个实例时记录它们(并防止垃圾收集其他未使用的实例),您可以简单地:

class Person
  @all = []
  def self.all; @all; end
  attr_accessor :name
  def initialize(name)
    @name = name
    self.class.all << self
  end
end

p1 = Person.new("joe")
p2 = Person.new("rick")
p Person.all
#=> [#<Person:0x007f9d1c8c4838 @name="joe">,
#=>  #<Person:0x007f9d1c8bb0d0 @name="rick">]

答案 2 :(得分:1)

我强制要在这里介绍my NameMagic

# first, gem install y_support
require 'y_support/name_magic'

class Person
  include NameMagic
  # here, Person receives for free the following functionality:
  # * ability to use :name (alias :ɴ) named argument in the constructor
  # * #name (alias #ɴ) instance method
  # * #name= naming / renaming method
  # * ability to name anonymous instances by merely assigning to constants
  # * collection of both named and anonymous instances inside the namespace
  # * hooks to modify the name, or do something else when the name is assigned
  # * ability to specify a different namespace than mother class for instance collection
end

Joe = Person.new #=> #<Person:0xb7ca89f8>
Rick = Person.new #=> #<Person:0xb7ca57bc>

Joe.name #=> :Joe
Rick.ɴ #=> :Rick
Person.instances # [#<Person:0xb7ca89f8>, #<Person:0xb7ca57bc>]
Person.instance_names # [:Joe, :Rick]

Person.new name: "Kit" #=> #<Person:0xb9776244>
Person.instance_names #=> [:Joe, :Rick, :Kit]
p3 = Person.instance( :Kit ) #=> #<Person:0xb9776244>
p2 = Person.instance( "Rick" ) #=> #<Person:0xb7ca57bc>
# Also works if the argument is already a Person instance:
p1 = Person.instance( Person.instance( :Joe ) ) #=> #<Person:0xb9515ba8>

anon = Person.new #=> #<Person:0xb9955c54>
Person.instances.size #=> 4
Person.instance_names #=> [:Joe, :Rick, :Kit]
anon.name = :Hugo
Person.instance_names #=> [:Joe, :Rick, :Kit, :Hugo]
Person::Hugo #=> #<Person:0xb9955c54>

关于垃圾收集的问题,可以忘记实例

Person.forget :Hugo #=> Returns, for the last time, "Hugo" instance
Person::Hugo #=> NameError
Person.forget_all_instances #=> [:Joe, :Rick, :Kit]
Person.instances #=> [] - everything is free to be GCed

引擎盖NameMagic使用与@sawa提议的方法相同的方法(至少在Ruby核心开发者提供const_assigned挂钩之前),即搜索整个ObjectSpace - 但不是对于母对象的实例,但对于名称空间(Module类对象),搜索其常量以查找分配给它们的未命名实例。