How to find each instance of a class in Ruby

2020-02-10 03:57发布

问题:

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.

回答1:

The solution is to use ObjectSpace.each_object method like

ObjectSpace.each_object(Pokemon) {|x| p x}

which produces

<Pokemon:0x0000010098aa70>
<Pokemon:0x00000100992158>
 => 2 

Details are discussed in the PickAxe book Chapter 25



回答2:

Yes, one could use ObjectSpace, but in practice one would simply keep track of instances as they are created.

class Pokemon
  @pokees = []
  self.class.public_send(:attr_reader, :pokees)

  def initialize
    self.class.pokees << self
  end
end

pikatchu = Pokemon.new
  #=> #<Pokemon:0x00005c46da66d640> 
charmander = Pokemon.new
  #=> #<Pokemon:0x00005c46da4cc7f0> 
Pokemon.pokees
  #=> [#<Pokemon:0x00005c46da66d640>, #<Pokemon:0x00005c46da4cc7f0>]