How do I list all objects created from a class in Ruby? [duplicate] How do I list all objects created from a class in Ruby? [duplicate] ruby ruby

How do I list all objects created from a class in Ruby? [duplicate]


You can use the ObjectSpace module to do this, specifically the each_object method.

ObjectSpace.each_object(Project).count

For completeness, here's how you would use that in your class (hat tip to sawa)

class Project  # ...  def self.all    ObjectSpace.each_object(self).to_a  end  def self.count    all.count  endend


One way to do is to keep track of it as and when you create new instances.

class Project    @@count = 0    @@instances = []    def initialize(options)           @@count += 1           @@instances << self    end    def self.all        @@instances.inspect    end    def self.count        @@count    endend

If you want to use ObjectSpace, then its

def self.count    ObjectSpace.each_object(self).countenddef self.all    ObjectSpace.each_object(self).to_aend


class Project    def self.all; ObjectSpace.each_object(self).to_a end    def self.count; all.length endend