Question

Why does ObjectSpace._id2ref give different outputs on Ruby 1.9 and Ruby 2.0?

Ruby 1.9.3p392 i386-mingw32

class Foo ; end

Foo.object_id                     #=> 17569464
ObjectSpace._id2ref(17569464)     #=> Foo

Foo.new.singleton_class.object_id #=> 17075124
ObjectSpace._id2ref(17075124)     #=> "\x00"

Ruby 2.0.0p0 i386-mingw32

class Foo ; end

Foo.object_id                     #=> 17197176
ObjectSpace._id2ref(17197176)     #=> Foo

Foo.new.singleton_class.object_id #=> 19181436
ObjectSpace._id2ref(19181436)     #=> RangeError: 0x124af7c is recycled object

Foo.new.singleton_class.object_id #=> 17454324
ObjectSpace._id2ref(17454324)     #=> RangeError: 0x10a54f4 is not id value

Foo.new.singleton_class.object_id #=> 17139816
ObjectSpace._id2ref(17139816)     #=> "c"
Was it helpful?

Solution

Just because in 2.0 the garbage collector was defter.

# RangeError: 0x124af7c is recycled object

states for the object was already GC’ed.

UPD: We can approach the requested behaviour with Mutex:

2.0.0 (main):0 > Mutex.new.synchronize {
2.0.0 (main):0 *   class Foo ; end
2.0.0 (main):0 *   id = Foo.new.singleton_class.object_id
2.0.0 (main):0 *   puts id
2.0.0 (main):0 *   puts ObjectSpace._id2ref(id)
2.0.0 (main):0 * }  
# 23172260
# <Class:#<Foo:0x00000002c32970>>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top