如何列出从Ruby中的类创建的所有对象? [英] How do I list all objects created from a class in Ruby?

查看:76
本文介绍了如何列出从Ruby中的类创建的所有对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby中,类是否可以通过某种方式知道它存在多少实例,并且可以列出它们?

Is there any way in Ruby for a class to know how many instances of it exist and can it list them?

这是一个示例类:

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

现在,我创建此类的项目对象:

Now I create project objects of this class:

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,以返回当前项目的列表和计数.

What I would like is to have class methods like Project.all and Project.count to return a listing and count of current projects.

我该怎么做?

推荐答案

您可以使用ObjectSpace模块执行此操作,特别是

You can use the ObjectSpace module to do this, specifically the each_object method.

ObjectSpace.each_object(Project).count

为完整起见,这是您在课堂上使用它的方式(向锯齿倾斜)

For completeness, here's how you would use that in your class (hat tip to sawa)

class Project
  # ...

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

  def self.count
    all.count
  end
end

这篇关于如何列出从Ruby中的类创建的所有对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆