如何在 Ruby 中获取类实例? [英] How to get class instances in Ruby?
本文介绍了如何在 Ruby 中获取类实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一个名为 Post 的类,它有许多已启动的实例(即 Post.new(:name => 'foo')
).
Say I have a class called Post that has many initiated instances (i.e. Post.new(:name => 'foo')
).
有没有办法通过调用某个类来检索该类的所有实例?我正在寻找类似 Post.instances.all
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
想法?
谢谢!
推荐答案
说明 alphazero 和 PreciousBodilyFluids 的答案:
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
这篇关于如何在 Ruby 中获取类实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文