Ruby有没有什么方法可以知道它有多少实例存在,并且可以列出它们?如何列出从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.all
和Project.count
返回的列表和当前项目的数量。
我该怎么做?
你是否需要在类中包含ObjectSpace以使其工作? – onebree
@HunterStevens不,我们不是将模块混入我们的课,只是调用它的一个方法 –
**警告**:这个解决方案可以很容易地在脚下自我射击。如果你不保留对你的对象的引用(例如,如果你没有将结果赋值给'Project.new'),它们将在某个时间点被垃圾回收,'ObjectSpace.each_object'显然会停止报告它们。使用'@@ instances = []'来代替rohit89的答案,通过保留对这些对象的引用来解决这个问题。 – vmarquet