在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
Run Code Online (Sandbox Code Playgroud)
现在我创建这个类的项目对象:
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)
Run Code Online (Sandbox Code Playgroud)
我想是有类方法一样Project.all,并Project.count返回一个列表和当前项目的计数.
我该怎么做呢?