33

クラスが存在するインスタンスの数を知るための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.allProject.countカウントを返すことです。

どうすればよいですか?

4

4 に答える 4

50

ObjectSpaceモジュールを使用してこれを行うことができます。具体的にはeach_objectメソッドです。

ObjectSpace.each_object(Project).count

完全を期すために、クラスでそれをどのように使用するかを次に示します(sawaのヒント)

class Project
  # ...

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

  def self.count
    all.count
  end
end
于 2013-01-14T12:50:06.103 に答える
7

そのための1つの方法は、新しいインスタンスを作成するときに、それを追跡することです。

class Project

    @@count = 0
    @@instances = []

    def initialize(options)
           @@count += 1
           @@instances << self
    end

    def self.all
        @@instances.inspect
    end

    def self.count
        @@count
    end

end

を使用したい場合ObjectSpaceは、

def self.count
    ObjectSpace.each_object(self).count
end

def self.all
    ObjectSpace.each_object(self).to_a
end
于 2013-01-14T12:24:27.687 に答える
4
class Project
    def self.all; ObjectSpace.each_object(self).to_a end
    def self.count; all.length end
end
于 2013-01-14T12:50:56.757 に答える
3

多分これはうまくいくでしょう:

class Project
  class << self; attr_accessor :instances; end

  attr_accessor :name, :tasks

  def initialize(options)
    @name = options[:name]
    @tasks = options[:tasks]

    self.class.instances ||= Array.new
    self.class.instances << self
  end

  def self.all
    # return listing of project objects
    instances ? instances.dup : []
  end

  def self.count
    # return a count of existing projects
    instances ? instances.count : 0 
  end

  def destroy
    self.class.instances.delete(self)
  end
end

ただし、これらのオブジェクトは手動で破棄する必要があります。たぶん、ObjectSpaceモジュールに基づいて他のソリューションを構築することができます。

于 2013-01-14T12:29:02.570 に答える