Alex Rivera | Logout

How to get class instances in Ruby?

Asked 2011-06-15T23:30:53.650
13

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

Edit
Report

1 Answer

20

Illustrating both alphazero's and PreciousBodilyFluids answers:

class Foo
  @@instance_collector = []
  def initialize
    @@instance_collector << self
    #other stuff
  end
  def self.all_offspring
    @@instance_collector
  end
end

a = Foo.new
b = Foo.new

p Foo.all_offspring  # => [#<Foo:0x886d67c>, #<Foo:0x886d668>]
p ObjectSpace.each_object(Foo).to_a # => [#<Foo:0x886d668>, #<Foo:0x886d67c>] #order is different
answered 2011-06-16T00:08:35.347

Your Answer