2

I've been trying to delete a class instance. Here's what I want:

class SomeClass
  def initialize
    some_stuff
  end
  def delete
    self.delete
  end
end

Calling SomeClass_instance.delete gives me:

SystemStackError: stack level too deep

Without the delete method defined, it gives me a NoMethodError.

Everything I try either gives me errors or does nothing. It would be great if somebody could explain how deleting a class instance works, or if it is possible.

Martin Evans
  • 45,791
  • 17
  • 81
  • 97
Dr. Hoenikker
  • 57
  • 2
  • 6
  • What is you want to achieve by `delete`? Why not just assign it to the `nil` ? – Roman Kiselenko Dec 11 '15 at 11:20
  • https://www.google.pl/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=delete%20class%20instalce%20ruby – Andrey Deineko Dec 11 '15 at 11:24
  • In the context of the method `delete`, `self.delete` is the same as calling `delete`, that's why you get a `SystemStackError`. It would be the same using a method called `foo` that calls `self.foo`. – Damiano Stoffie Dec 11 '15 at 11:27

1 Answers1

1

As you flagged the request with garbage-collection, I assume what you are trying to do is something similar to free in C.

Garbage collection in Ruby happens automatically. Once the object is no longer referenced anywhere in memory, the memory used by the object will be recollected in the next GC cycle.

You don't need to free the memory manually. Just make sure to not hold a reference to the object in a variable, especially in variables that live outside the scope of a method such as global variables, instance variables or class variables.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • I'm aware that GC happens automatically, but is simply deleting the reference itself enough? Say I have an instance "my_instance = Class.new" and I add "my_instance = nil", will this be enough to delete the reference? – Dr. Hoenikker Dec 11 '15 at 11:42
  • @Dr.Hoenikker: if there are no other references, then yes, that instance will be collected eventually. – Sergio Tulentsev Dec 11 '15 at 11:58
  • @Dr.Hoenikker: Not sure if **class objects** get the same treatment (in your sample line, `instance = Class.new`). I'm willing to bet that class objects go into some registry that keeps a reference to them. But your regular program won't create millions of dynamic throwaway classes. – Sergio Tulentsev Dec 11 '15 at 12:00