15

Why do system objects like nil, true or false have a fixed object id in Ruby. Also I tried printing out the object ids of numbers, they are the same and follow an odd number sequence pattern. Any explanation for this?

[nil,true,false].each { |o| print o.object_id, ' '}
4 2 0 => [nil, true, false]

>> (0..50).each { |i| print i.object_id, ' ' }
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99 101 => 0..50
dexter
  • 13,365
  • 5
  • 39
  • 56
  • 3
    possible duplicate of [Ruby - how does object_id assignment work?](http://stackoverflow.com/questions/3430280/ruby-how-does-object-id-assignment-work) – sepp2k Oct 17 '10 at 10:56

1 Answers1

21

The following two links explain the concept behind Ruby's object IDs:

http://www.oreillynet.com/ruby/blog/2006/01/the_ruby_value_1.html http://www.oreillynet.com/ruby/blog/2006/02/ruby_values_and_object_ids.html

The object ID is calculated from the objects value plus some additional information. From that calculation you can derive the values you are seeing in your examples.

James Sulak
  • 31,389
  • 11
  • 53
  • 57
Joachim
  • 550
  • 4
  • 9
  • 1
    links are dead, haven't find cached versions :| – NamiW Dec 04 '18 at 05:54
  • 4
    here's archive.org links for the articles - https://web.archive.org/web/20071226125820/http://www.oreillynet.com/ruby/blog/2006/01/the_ruby_value_1.html and https://web.archive.org/web/20071227161157/http://www.oreillynet.com:80/ruby/blog/2006/02/ruby_values_and_object_ids.html – spariev Dec 15 '18 at 21:03