Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get class instances in Ruby? [duplicate]

Say I have a class called Post that has many initiated instances (i.e. Post.new(:name => 'foo')).

Is there a way to retrieve all the instances of that class by calling something on it? I'm looking for something along the lines of Post.instances.all

like image 237
Yuval Karmi Avatar asked Jun 15 '11 23:06

Yuval Karmi


People also ask

What is DUP method in Ruby?

Ruby | Numeric dup() function The dup() is an inbuilt method in Ruby returns the number itself. Syntax: num1.dup() Parameters: The function needs a number. Return Value: It returns itself only.

How do I find the class of an object in Ruby?

Use #is_a? to Determine the Instance's Class Name in Ruby If the object given is an instance of a class , it returns true ; otherwise, it returns false .

What is instance of a class in Ruby?

Class Instances and Instance Methods In Ruby, a class is an object that defines a blueprint to create other objects. Classes define which methods are available on any instance of that class. Defining a method inside a class creates an instance method on that class.

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 ObjectSpace to retrieve all instantiated objects of a given class:

posts = []
ObjectSpace.each_object Post do |post|
  posts << post
end

This is almost certainly a bad idea, though - for example, it will also load Post instances that are still in memory from earlier requests that haven't been garbage-collected. There's probably a much better way to get at the posts you care about, but we'll need more information about what you're trying to do.

like image 109
PreciousBodilyFluids Avatar answered Sep 28 '22 11:09

PreciousBodilyFluids