【发布时间】:2012-12-28 09:23:31
【问题描述】:
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 这样的类方法来返回当前项目的列表和计数。
我该怎么做?
【问题讨论】:
标签: ruby oop class-method