如何在Ruby中列出从类创建的所有对象?

时间:2013-01-14 12:02:39

标签: ruby oop class-method

Ruby中是否有任何方法可以让一个类知道它有多少个实例并且可以列出它们?

以下是一个示例类:

class Project

  attr_accessor :name, :tasks

  def initialize(options)
    @name = options[:name]
    @tasks = options[:tasks]
  end

  def self.all
    # return listing of project objects
  end

    def self.count
          # return a count of existing projects
    end


end

现在我创建这个类的项目对象:

options1 = {
  name: 'Building house',
  priority: 2,
  tasks: []
}

options2 = {
  name: 'Getting a loan from the Bank',
  priority: 3,
  tasks: []
}

@project1 = Project.new(options1)
@project2 = Project.new(options2)

我想要的是让Project.allProject.count等类方法返回当前项目的列表和计数。

我该怎么做?

4 个答案:

答案 0 :(得分:42)

您可以使用ObjectSpace模块执行此操作,尤其是each_object方法。

ObjectSpace.each_object(Project).count

为了完整起见,这里是你如何在课堂上使用它(帽子提示sawa)

class Project
  # ...

  def self.all
    ObjectSpace.each_object(self).to_a
  end

  def self.count
    all.count
  end
end

答案 1 :(得分:7)

一种方法是在创建新实例时跟踪它。

class Project

    @@count = 0
    @@instances = []

    def initialize(options)
           @@count += 1
           @@instances << self
    end

    def self.all
        @@instances.inspect
    end

    def self.count
        @@count
    end

end

如果您想使用ObjectSpace,那么

def self.count
    ObjectSpace.each_object(self).count
end

def self.all
    ObjectSpace.each_object(self).to_a
end

答案 2 :(得分:4)

class Project
    def self.all; ObjectSpace.each_object(self).to_a end
    def self.count; all.length end
end

答案 3 :(得分:2)

也许这会奏效:

class Project
  class << self; attr_accessor :instances; end

  attr_accessor :name, :tasks

  def initialize(options)
    @name = options[:name]
    @tasks = options[:tasks]

    self.class.instances ||= Array.new
    self.class.instances << self
  end

  def self.all
    # return listing of project objects
    instances ? instances.dup : []
  end

  def self.count
    # return a count of existing projects
    instances ? instances.count : 0 
  end

  def destroy
    self.class.instances.delete(self)
  end
end

但是你必须手动销毁这些对象。也许可以基于ObjectSpace模块构建其他解决方案。