2

object_id of a Fixnum is an odd number:

i=0; i += 1 while i.object_id.odd?
# ^CIRB::Abort: abort then interrupt!
i # => 495394962

while it seems that the object_id of any other object is an even number (Bignum included):

{}.object_id # => 70230978908220
true.object_id # => 20
false.object_id # => 0
nil.object_id # => 8
/regexp/.object_id # => 70230978711620
:symbol.object_id # => 391528
{/regexp/mou => Struct.new(:hello)}.object_id # => 70230987100840

Does this have something to do with some obscure optimization within the Ruby interpreter?

sawa
  • 165,429
  • 45
  • 277
  • 381
yeyo
  • 2,954
  • 2
  • 29
  • 40
  • @CarySwoveland `0.object_id` yields `1` (in my irb session). Maybe this is something related to the ruby version I'm using. – yeyo Apr 04 '15 at 21:31
  • Symbols and floats (except possibly really large ones) seem to have even object id's. – Cary Swoveland Apr 04 '15 at 21:36

1 Answers1

7

This is done so that integers do not take up all the room for other objects. In Ruby all other Objects have even object_id's, they go in between. The integer object_id's are very easily converted to their value: the last bit (always a 1) is chopped off.

Integers are a bit fake objects, they are no more than an id and a shared list of methods.

steenslag
  • 79,051
  • 16
  • 138
  • 171
  • That makes sense. Do you know how that relates to other immediate objects, like symbols and floats, are handled? – Cary Swoveland Apr 04 '15 at 21:47
  • @CarySwoveland No. I don't even know what immediate objects are. nil, true and false seem to have fixed id's. – steenslag Apr 04 '15 at 21:53
  • 3
    Note that this is an internal private implementation detail of YARV. Other Ruby implementations may or may not follow the same pattern. All that is guaranteed by Ruby is 1) the same object has the same `object_id` during its lifetime and 2) at no time do two different objects have the same `object_id` at the same time. (Note, however, that two different objects may have the same `object_id` at different times, i.e. `object_id`s may be recycled). Everything else is up to the implementor. The specific case here is that YARV simply uses the memory address as the `object_id` and uses a tagged … – Jörg W Mittag Apr 04 '15 at 22:25
  • … pointer representation for `Fixnum`s. I explained tagged pointer representation here: http://stackoverflow.com/a/3774467/2988 – Jörg W Mittag Apr 04 '15 at 22:26
  • @JörgWMittag I did read your explanation at least a year ago. I've read a many of your answers and learnt a lot. Thanks. – steenslag Apr 04 '15 at 22:46