Why isn't my Ruby object deleted when the last reference goes out of scope?

Posted by Andrew Clegg on Stack Overflow See other posts from Stack Overflow or by Andrew Clegg
Published on 2010-04-04T19:06:22Z Indexed on 2010/04/04 19:13 UTC
Read the original article Hit count: 227

Filed under:
|
|

Hi gurus, I've found a weird effect when trying to track down a memory leak in a Rails app. Can anyone explain what's going on here?

Save this script as a plain Ruby script (Rails not necessary):

class Fnord
    def to_s
        'fnord'
    end
end

def test
    f = Fnord.new
end

test

GC.start
sleep 2

ObjectSpace.each_object do |o|
    puts o if o.is_a? Fnord
end

When I run this via

ruby 1.8.7 (2009-06-12 patchlevel 174) [i486-linux]

I get the following:

bash $ ruby var_test
fnord

Although the variable f is out of scope, there are no other references to the single Fnord object, and I've garbage collected, the object still seems to exist. Is this a nefarious memory leak of some sort, or am I completely missing something about Ruby?

Further, if I change the test method to this:

def test
    f = Fnord.new
    f = nil
end

I get no output. But surely this should not change the semantics here?

Many thanks!

© Stack Overflow or respective owner

Related posts about ruby

Related posts about scoping