I'm playing around with Ruby's .object_id
and noticed that, in several sequential sessions of irb, I get these identical results:
false.object_id // 0 true.object_id // 2 nil.object_id // 4 100.object_id // 201
In fact, every integer's object_id seems to be ((value * 2) + 1).
On the other hand, a given string's object_id is never the same after exiting and re-running irb.
This raises several questions for me:
object_id
s are determined? Are others basically random?Using Andrew Grimm's suggestion, I tried discovering other "low id" objects, but found that:
Object_ID is a unique id number for an object within the database, this is used internally by SQL Server. It should be noted, not all objects have an object_id. DDL triggers for example do not as they are not schema-scoped.
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.
objects catalog view, obtain the object identification numbers by querying the appropriate catalog view. For example, to return the object identification number of a DDL trigger, use SELECT OBJECT_ID FROM sys. triggers WHERE name = 'DatabaseTriggerLog``' .
In MRI the object_id
of an object is the same as the VALUE
that represents the object on the C level. For most kinds of objects this VALUE
is a pointer to a location in memory where the actual object data is stored. Obviously this will be different during multiple runs because it only depends on where the system decided to allocate the memory, not on any property of the object itself.
However for performance reasons true
, false
, nil
and Fixnum
s are handled specially. For these objects there isn't actually a struct with the object's data in memory. All of the object's data is encoded in the VALUE
itself. As you already figured out the values for false
, true
, nil
and any Fixnum
i
, are 0
, 2
, 4
and i*2+1
respectively.
The reason that this works is that on any systems that MRI runs on, 0
, 2
, 4
and i*2+1
are never valid addresses for an object on the heap, so there's no overlap with pointers to object data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With