How to get class instances in Ruby? [duplicate]

You can use ObjectSpace to retrieve all instantiated objects of a given class:

posts = []
ObjectSpace.each_object Post do |post|
  posts << post
end

This is almost certainly a bad idea, though – for example, it will also load Post instances that are still in memory from earlier requests that haven’t been garbage-collected. There’s probably a much better way to get at the posts you care about, but we’ll need more information about what you’re trying to do.

Leave a Comment