[Ruby] Ghetto

Mike Mondragon mikemondragon at gmail.com
Thu Jan 3 09:23:22 PST 2008


On 1/3/08, javier ramirez <jramirez at aspgems.com> wrote:
> Hi,
> > Ruby has a conservative GC.  This means it won't necessarily ever kill
> > an object, even if all references are gone.
> >
> the above is true, and in this case you are doing something a bit weird
> and probably the GC is not sure how to proceed, so it will act
> conservative. You are creating an instance of user without assigning it
> to any variable, so there will not be references to the object_id
> associated to any variables for the GC to check. My guess is that's
> probably causing a bit of confussion for the GC.
>
> I just checked if you modify your code and assign the new object to a
> variable, then the GC will do his part as expected
>
> class User; end
> user = User.new  #here i assign the new object to a variable. Reference count for the object_id will be increase
> user = nil       #here we are decreasing the reference count for that object
>
> GC.start        # reference count for that object_id should be 0 by now, so GC will remove it (probably, GCs have a strong personality ;)  )
>
> ObjectSpace.each_object do |object|
>   user = object if object.class.to_s == 'User'
> end
> p user          #we get a nil here, as expected
>
>
>
> regards,
>
> javier ramírez

I'm assuming you executed your code in irb, if you did the printing of
the user part would have looked something like:
~$ irb
irb(main):001:0> class User; end
=> nil
irb(main):002:0> User.new
=> #<User:0xb7c80d7c>
irb(main):003:0> GC.start
=> nil
irb(main):004:0> user = nil
=> nil
irb(main):005:0> ObjectSpace.each_object do |object|
irb(main):006:1*  user = object if object.class.to_s == 'User'
irb(main):007:1> end
=> 11085
irb(main):008:0> p user
#<User:0xb7c80d7c>
=> nil
irb(main):009:0>

p returns nil, the object assigned to the user variable is not nil.

Anyway, Eric explained what is going on with the reference in the C stack


More information about the Ruby mailing list