Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there any way in Ruby for a class to know how many instances of it exist and can it list them?

Here is a sample class:

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 

Now I create project objects of this class:

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) 

What I would like is to have class methods like Project.all and Project.count to return a listing and count of current projects.

How do I do this?

like image 649
Amit Erandole Avatar asked Jan 14 '13 12:01

Amit Erandole


People also ask

How do you create an array of objects from a class in Ruby?

You can create an array by separating values by commas and enclosing your list with square brackets. In Ruby, arrays always keep their order unless you do something to change the order. They are zero-based, so the array index starts at 0.

What does .class mean in Ruby?

What is a class in Ruby? Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects. Objects are the products of the class.

What is the difference between a class and a module Ruby?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).

What is super class in Ruby?

Ruby uses the super keyword to call the superclass implementation of the current method. Within the body of a method, calls to super acts just like a call to that original method. The search for a method body starts in the superclass of the object that was found to contain the original method.


1 Answers

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 
like image 103
Andrew Haines Avatar answered Sep 20 '22 20:09

Andrew Haines