Dribbler
Dribbler

Reputation: 4681

Does this Array.new in a loop create a memory leak?

I know how I'd do this in C++, but in Ruby, I'm not so sure. This is basically the structure that I'm working with (except that instead of integers, I have 2 element arrays contained within the array data.)

data = [ 1, 2, 3 ]

while true do
    wrong = Array.new
    data.each do |d|
        print "Guess: "
        guess = gets
        if guess.strip.to_i == d
            puts "Correct!"
        else
            puts "Sorry, the right answer is #{ d }."
            wrong << d
        end
    end

    if wrong.length == 0
        break
    else
        data = wrong
    end
end

Am I creating a memory leak by Array.new in each loop? Is there an alternative approach that is more efficient?

Thanks in advance!

Upvotes: 1

Views: 201

Answers (2)

lwassink
lwassink

Reputation: 1691

Ruby allows parallel assignment, so swapping the values of data and wrong is as easy as

data, wrong = wrong, data

You aren't creating a memory leak by calling Array.new because ruby has automatic garbage collection, so it will delete the old arrays once the program no longer holds a reference to them.

Upvotes: 2

John Wyatt
John Wyatt

Reputation: 69

No, Ruby has a garbage collector. The basic design of a garbage collector is that objects are checked to see if they have gone out of scope like your "wrong" variable, and, if not referenced by another object are marked to be deleted (freed).

Ruby and other languages now have more complex garbage collectors and those who work on them for a living can poke holes in the simple explanation I gave, but this is the basic idea.

Upvotes: 1

Related Questions