From: Charles Oliver Nutter Date: 2010-04-25T16:52:00+09:00 Subject: Re: #object_hexid On Sat, Apr 24, 2010 at 9:09 AM, Intransition wrote: > I recently got an error report from someone using 1.8.6: > >  1) Failure: test_object_hexid(TCKernel) [./test/core/kernel/ > test_object_hexid.rb:8]: >  <"#"> expected but was >  <"#">. > > I know what's causing this in my current implementation, but I've been > down this road before -- I tweak the implementation to satisfy one > error report and another seems to crop up. So I was hoping someone > might have a definitive answer. I think you're going to be SOL expecting these values to always match up across implementations. They are fortunately the same or similar in C Ruby versions because C Ruby uses the pointer address of the object for that hex number. On implementations where objects can move in memory, that value is almost always going to be calculated and potentially not even unique. In JRuby, the inspect value is based on the "identity hashcode" of the object, which is the default hashcode value the object would have it if did not override and provide its own hashcode. It is not guaranteed to be unique. Because of that, JRuby uses a strictly-increasing counter for object_id's as they are requested, and so object_id is entirely unrelated to the inspect hash string. I suspect other implementations with relocating objects will have similar limitations on the uniqueness and equivalence of these various values. If you really want a unique hexid you can use for a given object, calculate it and stuff it into the object when it's first requested: class Object def hexid # not thread-safe, but wasting an ID isn't a big deal @hexid ||= Object.calculate_hexid @hexid.to_s(16) end def self.calculate_hexid # appropriate mutexing should surround this @next_hexid += 1 end end Or on an impl like JRuby, where object_id is guaranteed not to produce a duplicate value (or at least, not up to 2^64 object_id's), just use object_id directly. > >> Is it important that object_hexid returns the same value as reported by >> #inspect, or just some unique id? > > Yes. I guarantee this won't ever work in JRuby and may not work on anything but C Ruby. I think you're asking too much of that inspect value. Can you describe *why* you need this behavior? - Charlie