Ollie H-M
Ollie H-M

Reputation: 495

In ruby, can objects assigned to a variable in a class method be garbage collected?

I know that objects assigned to a Constant cannot be garbage collected. ("Constants in Ruby are never garbage collected so if a constant has a reference to an object, then that object can never be garbage collected." - https://www.sitepoint.com/ruby-uses-memory/)

But I'm trying to get clarity for my peace of mind on what other things in general will never be garbage collected.

In particular, can objects assigned to a plain variable in a class method be garbage collected? For example:

class Foo
  def self.bar
    array = []
    1000.times { array << 'string' }
  end
end

After Foo.bar is called, can those 1000 strings be garbage collected, or do they have to hang around because they are stored against the 'array' variable?

And what would be the case if array were @array or @@array?

Upvotes: 1

Views: 736

Answers (1)

Cyzanfar
Cyzanfar

Reputation: 7136

The GC checks which of the slots/objects are not being referenced by other objects anymore and frees them. So in your particular case array isn't being referenced anywhere so it will be garbage collected. Here's an article explaining how GC works.

A class instance variable @instance and a class variable @@instance holds a reference to its class vars which prevents their garbage collection until the class itself is undefined.

Upvotes: 2

Related Questions