Alex Alex - 3 months ago 24
Ruby Question

Ruby - Iterating over Instances

Do instances of classes get an index set to them? And if so, would it be possible to iterate over them much like arrays in order to compress down the amount of lines of code I'm using? At the moment, my program has over 100 instances of a class and I want to write a loop so the code isn't basically just an enormous list of 'Class#new's! It kind of defeats the purpose of making the class itself in the first place (not really, but you get the idea).

Answer

You can use ObjectSpace to retrieve all instantiated objects of a given class: let say you have a class named MyClass and you want all the instances of that class then

ObjectSpace.each_object(MyClass) do |obj|
  #do what ever you want to do with that object
end

how ever this is a bad idea to do it. it will also load MyClass instances that are still in memory from earlier requests that haven't been garbage-collected.