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
返回当前项目的列表和计数。
我该怎么做呢?