Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, why does inspect() print out some kind of object id which is different from what object_id() gives?

When the p function is used to print out an object, it may give an ID, and it is different from what object_id() gives. What is the reason for the different numbers?

Update: 0x4684abc is different from 36971870, which is 0x234255E

>> a = Point.new => #<Point:0x4684abc>  >> a.object_id => 36971870  >> a.__id__ => 36971870  >> "%X" % a.object_id => "234255E" 
like image 472
nonopolarity Avatar asked May 12 '10 12:05

nonopolarity


People also ask

What is Ruby object id?

For every object, Ruby offers a method called object_id. You guessed it, this represents a random id for the specific object. This value is a reference of the address in memory where the object is store. Every object has a unique object id that will not change throughout the life of this object.

What does inspect method do Ruby?

inspect is a String class method in Ruby which is used to return a printable version of the given string, surrounded by quote marks, with special characters escaped.

What is inspect in rails?

inspect() public. Returns a string containing a human-readable representation of obj. The default inspect shows the object's class name, an encoding of the object id, and a list of the instance variables and their values (by calling #inspect on each of them).


1 Answers

The default implementation of inspect calls the default implementation of to_s, which just shows the hexadecimal value of the object directly, as seen in the Object#to_s docs (click on the method description to reveal the source).

Meanwhile the comments in the C source underlying the implementation of object_id shows that there are different “namespaces” for Ruby values and object ids, depending on the type of the object (e.g. the lowest bit seems to be zero for all but Fixnums). You can see that in Object#object_id docs (click to reveal the source).

From there we can see that in the “object id space” (returned by object_id) the ids of objects start from the second bit on the right (with the first bit being zero), but in “value space” (used by inspect) they start from the third bit on the right (with the first two bits zero). So, to convert the values from the “object id space” to the “value space”, we can shift the object_id to the left by one bit and get the same result that is shown by inspect:

> '%x' % (36971870 << 1) => "4684abc"  > a = Foo.new => #<Foo:0x5cfe4> > '%x' % (a.object_id << 1) => "5cfe4" 
like image 96
Arkku Avatar answered Sep 21 '22 21:09

Arkku