Ruby automatically reclaims unused memory

In languages like C and C++, memory allocation and deallocation must be handled manually. Ruby, however, features automatic memory management through a garbage collector, eliminating the need for explicit allocation or deallocation (as do many other garbage-collected languages).

Below is a simple Person class that takes name and age as parameters:

class Person
	def initialize(name, age)
		@name = name
		@age = age
	end

	def to_s
		puts "Name: #{@name}  Age: #{@age}"
	end
end

10.times do |i|
	person = Person.new("madelen#{i}", 17 + i.to_i)
	person.to_s
end

In this loop, a new Person object is created on each iteration, but there’s no explicit deletion or memory deallocation. Will this cause a memory leak? No.

Ruby’s garbage collector automatically reclaims memory from objects that are no longer accessible. When a new object is assigned to the person variable in each iteration, the previously assigned object becomes unreachable. Once no references remain, Ruby’s garbage collector removes it and frees the memory.

Backlinks: