How to find each instance of a class in Ruby

后端 未结 4 1025
無奈伤痛
無奈伤痛 2020-12-09 10:30

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         


        
4条回答
  •  抹茶落季
    2020-12-09 11:11

    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
      #=> # 
    charmander = Pokemon.new
      #=> # 
    Pokemon.pokees
      #=> [#, #] 
    

提交回复
热议问题