Harish Shetty
Harish Shetty

Reputation: 64363

When are constants garbage collected in Ruby?

  1. When does the Class object assigned to a constant get garbage collected? E.g.

    class Foo; end
    Bar = Class.new {}
    
  2. When does a constant declared inside an anonymous class/module get garbage collected? E.g.

    foo = Class.new do
      self::NAME = "Bar"
    end
    foo::NAME  # Bar
    foo = nil 
    GC.start 
    

    In the example above, will the constant NAME declared inside the anonymous class be garbage collected? ( I am assuming the anonymous class will be garbage collected..)

Upvotes: 7

Views: 924

Answers (1)

Andrew Marshall
Andrew Marshall

Reputation: 96994

It’s easy to boil this down to the very general case: if an object no longer has any references to it, it can be garbage collected. Note that I say object, not variable. Variables are not garbage collected, objects are.


Now let’s look at your given examples:

class Foo; end
Bar = Class.new {}

Instances of Class will only be garbage collected if the constant they’re assigned to (if any) is reassigned to a different value (e.g. Bar = nil) and there are no instances of that class and there are no Classes which inherit from it.

foo = Class.new do
  self::NAME = "Bar"
end
foo::NAME  # Bar
foo = nil

The values previously in foo & foo::NAME can be garbage collected if there were no other references to them (i.e. this snippet is the complete code).

Upvotes: 6

Related Questions