在 Ruby 中,为什么 inspect() 打印出某种与 object_id() 给出的不同的对象 id? [英] In Ruby, why does inspect() print out some kind of object id which is different from what object_id() gives?

查看:77
本文介绍了在 Ruby 中,为什么 inspect() 打印出某种与 object_id() 给出的不同的对象 id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

p函数用于打印对象时,可能会给出一个ID,与object_id()给出的不同.数字不同的原因是什么?

When the p function is used to print out an object, it may give an ID, and it is different from what object_id() gives. What is the reason for the different numbers?

更新: 0x4684abc36971870 不同,后者是 0x234255E

Update: 0x4684abc is different from 36971870, which is 0x234255E

>> a = Point.new
=> #<Point:0x4684abc>

>> a.object_id
=> 36971870

>> a.__id__
=> 36971870

>> "%X" % a.object_id
=> "234255E"

推荐答案

inspect 的默认实现调用了 to_s 的默认实现,它只是显示的十六进制值对象直接,如在 Object#to_s docs(点击方法描述以显示来源).

The default implementation of inspect calls the default implementation of to_s, which just shows the hexadecimal value of the object directly, as seen in the Object#to_s docs (click on the method description to reveal the source).

同时,object_id 实现底层的 C 源代码中的注释表明,Ruby 值和对象 id 有不同的命名空间",这取决于对象的类型(例如,最低位似乎是对于除 Fixnums 之外的所有值都为零).您可以在 Object#object_id docs(点击显示来源).

Meanwhile the comments in the C source underlying the implementation of object_id shows that there are different "namespaces" for Ruby values and object ids, depending on the type of the object (e.g. the lowest bit seems to be zero for all but Fixnums). You can see that in Object#object_id docs (click to reveal the source).

从那里我们可以看到,在对象id空间"(由object_id返回)中,对象的id从右边的第二位开始(第一位为零),但是在值空间"(由 inspect 使用)中,它们从右边的第三位开始(前两位为零).因此,要将值从object id space"转换为value space",我们可以将 object_id 向左移动一位,得到与 所示相同的结果检查:

From there we can see that in the "object id space" (returned by object_id) the ids of objects start from the second bit on the right (with the first bit being zero), but in "value space" (used by inspect) they start from the third bit on the right (with the first two bits zero). So, to convert the values from the "object id space" to the "value space", we can shift the object_id to the left by one bit and get the same result that is shown by inspect:

> '%x' % (36971870 << 1)
=> "4684abc"

> a = Foo.new
=> #<Foo:0x5cfe4>
> '%x' % (a.object_id << 1)
=> "5cfe4"

这篇关于在 Ruby 中,为什么 inspect() 打印出某种与 object_id() 给出的不同的对象 id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆