修复了Ruby中系统对象和小整数的对象ID

dex*_*ter 15 ruby language-features programming-languages language-design

为什么像nil,true或false这样的系统对象在Ruby中具有固定的对象id.此外,我尝试打印出数字的对象ID,它们是相同的并遵循奇数序列模式.对此有何解释?

[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
Run Code Online (Sandbox Code Playgroud)

Joa*_*him 21

以下两个链接解释了Ruby的对象ID背后的概念:

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

对象ID是根据对象值加上一些附加信息计算出来的.从该计算中,您可以导出您在示例中看到的值.

  • 这是文章的 archive.org 链接 - https://web.archive.org/web/20071226125820/http://www.oreillynet.com/ruby/blog/2006/01/the_ruby_value_1.html 和 https://web .archive.org/web/20071227161157/http://www.oreillynet.com:80/ruby/blog/2006/02/ruby_values_and_object_ids.html (2认同)