How to destroy Ruby object? How to destroy Ruby object? ruby ruby

How to destroy Ruby object?


Other than hacking the underlying C code, no. Garbage collection is managed by the runtime so you don't have to worry about it. Here is a decent reference on the algorithm in Ruby 2.0.

Once you have no more references to the object in memory, the garbage collector will go to work. You should be fine.


The simple answer is, let the GC (garbage collector) do its job.

When you are ready to get rid of that reference, just do object = nil. And don't make reference to the object.

The garbage collector will eventually collect that and clear the reference.

(from ruby site)=== Implementation from GC------------------------------------------------------------------------------  GC.start                     -> nil  GC.start(full_mark: true, immediate_sweep: true)           -> nil------------------------------------------------------------------------------Initiates garbage collection, unless manually disabled.This method is defined with keyword arguments that default to true:  def GC.start(full_mark: true, immediate_sweep: true); endUse full_mark: false to perform a minor GC. Use immediate_sweep: false todefer sweeping (use lazy sweep).Note: These keyword arguments are implementation and version dependent. Theyare not guaranteed to be future-compatible, and may be ignored if theunderlying implementation does not support them.


Ruby Manages Garbage Collection Automatically

For the most part, Ruby handles garbage collection automatically. There are some edge cases, of course, but in the general case you should never have to worry about garbage collection in a typical Ruby application.

Implementation details of garbage collection vary between versions of Ruby, but it exposes very few knobs to twiddle and for most purposes you don't need them. If you find yourself under memory pressure, you may want to re-evaluate your design decisions rather than trying to manage the symptom of excess memory consumption.

Manually Trigger Garbage Collection

In general terms, Ruby marks objects for garbage collection when they go out of scope or are no longer referenced. However, some objects such as Symbols never get collected, and persist for the entire run-time of your program.

You can manually trigger garbage collection with GC#start, but can't really free blocks of memory the way you can with C programs from within Ruby. If you find yourself needing to do this, you may want to solve the underlying X/Y problem rather than trying to manage memory directly.