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
  end
end

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)