开发者

How to get class instances in Ruby? [duplicate]

This question already has answers here: How to find each instance of a class in Ruby (4 answers) 开发者_如何学Go Closed 7 years ago.

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


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.


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


Override new; keep count; expose property.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜