From: Intransition Date: 2010-04-24T23:09:49+09:00 Subject: Re: #object_hexid On Apr 24, 9:31 am, Brian Candler wrote: > Thomas Sawyer 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. > > Can you show the failing examples? Is the portability problem between > ruby 1.8.x and 1.9.x, or are you trying to make portable with JRuby, > Rubinius, MacRuby etc? That would be nice. 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. > Is it important that object_hexid returns the same value as reported by > #inspect, or just some unique id? Yes. > The obvious would be something like: > > >> module Kernel > >> def object_hexid(o) > >> o.object_id.to_s(16) > >> end > >> end > => nil > >> object_hexid("") > > => "3faf23593bf4" > > but I've not tested that on any more than MRI 1.8.7, and the hex ID is > not the same as #inspect: > > >> class Foo; end > => nil > >> f = Foo.new > > => #>> object_hexid(f) > > => "3faf2358e0b4" Right. You have to shift the value one unit like Dominik's version. At this point I think I am just going to go with the simple solution: "0x" << (__id__ << 1).to_s(16) Previous error reports seem to be 1.8.6 related, and at this point I think I will only support 1.8.7+. Hopefully the above definition is consistent for all implementations. I think it would be nice if this method was already provided -- I find it helpful in cases where I write a custom #inspect method, but still wish to imitate Ruby's usual format.