0

Someone used the phrase "destroy a class" and I was skeptical that it meant anything at all, and decided to do a search and it looks like destroying classes seems to be an actual concept, as shown in How to properly destroy a class

What does it mean to destroy a class?
How would I destroy a class in Ruby? (if that makes sense at all)

  • You shouldn't be promoting class warfare. – Cary Swoveland Nov 23 '13 at 7:33
3

Rather destroying, you may remove the constant. Remember class(s) are nothing but constants.

class C;end
C.name # => "C"

self.class.send(:remove_const,:C) 
C.name # uninitialized constant C (NameError)

When you are doing class C;end, it means you are creating the instance of Class(constant assignment) and assigning that instance to constant C. #remove_const method actually doing the un-assignment, and returns the Class instance, which you can assign to another constant.

class C
  def self.foo
    12
  end
end

C.foo # => 12
M = self.class.send(:remove_const,:C) 
M.foo # => 12
C.foo # uninitialized constant C (NameError)
| improve this answer | |
1

The most important rule to learn is, that in Ruby, destroying classes is no different from destroying any other objects. Usually, you have a few fixed classes assigned to constants, that are never destroyed. It is a good, but fairly underused practice to create parametrized subclasses, also of class Class, which may get destroyed during the program execution, just like any other object. The destruction itself is performed by the garbage collector, which is normally of no concern to the programmer.

Note: The article you link to does not talk about destroying classes, but about instantiating and destroying the instances.

| improve this answer | |
  • But aren't classes instances of class Class themselves? – user2422869 Nov 23 '13 at 6:50
  • Yes, they are. Even class Class itself is an instance of class Class, that is, itself. – Boris Stitnicky Nov 23 '13 at 7:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.