Ruby 中系统对象和小整数的固定对象 ID
为什么像 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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
以下两个链接解释了 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 是根据对象值加上一些附加信息计算得出的。从该计算中,您可以得出示例中看到的值。
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.