Is there a way to get all the objects that are of a certain class in Ruby?
To clarify:
class Pokemon
end
pikatchu = Pokemon.new
charmander = Pokemon.new
So, is there a way I could somehow retrieve references those two objects (pikatchu
and charmander
)?
I actually thought of shoving it all into a class array via initialize, but that could potentially grow big, and I am assuming there might be a native Ruby approach to it.
Yes, one could use
ObjectSpace
, but in practice one would simply keep track of instances as they are created.The solution is to use
ObjectSpace.each_object
method likewhich produces
Details are discussed in the PickAxe book Chapter 25