How to find each instance of a class in Ruby

后端 未结 4 1058
無奈伤痛
無奈伤痛 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:06

    The solution is to use ObjectSpace.each_object method like

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

    which produces

    
    
     => 2 
    

    Details are discussed in the PickAxe book Chapter 25

提交回复
热议问题