From: Colin Bartlett Date: 2010-04-24T23:36:14+09:00 Subject: Re: #object_hexid On Sat, Apr 24, 2010 at 2:16 PM, Intransition wrote: > Can anyone write a reliable Kernel#object_hexid, a method that returns > an object's id but in hex, just like Ruby's normal #inspect provides. > My attempts seems to break depending on the version of Ruby used. That's something I've wanted when I've been writing #inspect for a class, and (for aesthetics!) I've wanted the object_id encoding in the default #inspect. Give that there must (I assume) be a function in the underlying C or Java (etc) code to produce the object_id encoding, are there any reasons why that should not also be a method in Object? (The C code for 1.9.1 seems to encode c pointer to the object?) On Sat, Apr 24, 2010 at 2:22 PM, Dominik Honnef wrote: > "0x%x" % (object_id << 1) > should work univerally, I guess. It seems to work in Ruby 1.8.6 and 1.9.1, but not in JRuby? (See below.) On Sat, Apr 24, 2010 at 2:31 PM, Brian Candler wrote: > Is it important that object_hexid returns the same value as reported by > #inspect, or just some unique id? I'm not sure (for me, anyway) it's vital that it's the same value as #inspect. But I've been wondering why (as your code showed) that the hexid in #inspect is different to #object_id.to_s(16). Can anyone give reasons? (I've just had a quick look at the code in object.c, and a few other *.c which included object_id or inspect/to_s, and nothing obvious struck me. I must confess I found the code not easy to follow, but I only speak pidgin C.) # code comparing the #inspect encoding of object_id with the object_id class Q; end q = Q.new iid = q.inspect ; iid[-1, 1] = "" ; iid[0, 4] = "" oid = q.object_id puts "inspect #=> " + q.inspect puts "inspect id #=> " + iid puts "oid << 1 #=> 0x" + (oid << 1 ).to_s(16) puts "Integer(iid) #=> " + Integer(iid).to_s puts "oid #=> #=> " + oid.to_s ruby 1.9.1p243 (2009-07-16 revision 24175) [i386-mingw32] inspect #=> # inspect id #=> 0x2205b80 oid << 1 #=> 0x2205b80 Integer(iid) #=> 35675008 oid #=> #=> 17837504 jruby 1.5.0.RC1 (ruby 1.8.7 patchlevel 249) (2010-04-14 0b08bc7) (Java HotSpot(TM) Client VM 1.6.0_14) [x86-java] inspect #=> # inspect id #=> 0x16fdac oid << 1 #=> 0xfb8 Integer(iid) #=> 1506732 oid #=> #=> 2012