Ruby ਮੈਮੋਰੀ ਨੂੰ ਆਪਣੇ-ਆਪ ਇੱਕ garbage collector (GC) ਦੇ ਜ਼ਰੀਏ ਪ੍ਰਬੰਧਿਤ ਕਰਦਾ ਹੈ ਜੋ ਉਹਨਾਂ ਚੀਜ਼ਾਂ ਨੂੰ ਮੁਕਤ ਕਰਦਾ ਹੈ ਜਿਨ੍ਹਾਂ ਦਾ ਕੋਈ reference ਨਹੀਂ ਰਿਹਾ। ਆਧੁਨਿਕ Ruby (MRI) ਇੱਕ generational, incremental mark-and-sweep collector ਦੀ ਵਰਤੋਂ ਕਰਦਾ ਹੈ ਜਿਸ ਵਿੱਚ compaction ਹੈ। ਇਸ ਨੂੰ ਸਮਝਣਾ performance ਅਤੇ ਲੰਬੇ ਸਮੇਂ ਚਲਣ ਵਾਲੀਆਂ ਐਪਲੀਕੇਸਨਾਂ ਵਿੱਚ ਮੈਮੋਰੀ ਦੀਆਂ ਸਮੱਸਿਆਵਾਂ ਦਾ ਨਿਦਾਨ ਕਰਨ ਵਿੱਚ ਸਹਾਇਕ ਹੁੰਦਾ ਹੈ।
Automatic garbage collection
Ruby allocates objects on the heap; the GC reclaims those that are no longer REACHABLE
(referenced). You never free memory manually.
Modern MRI GC characteristics:
✓ Mark-and-sweep — marks reachable objects (from roots), sweeps unreachable ones
✓ Generational (since Ruby 2.1) — new objects collected often, old ones rarely
(based on "most objects die young")
✓ Incremental — spreads GC work to reduce pause times
✓ Compacting (GC.compact, Ruby 2.7+) — reduces memory fragmentation
