简体   繁体   English

object_id 方法与 Fixnum 对象和 String 对象的工作差异

[英]Difference on working of object_id method with Fixnum object and String object

I am confused about the working of one of the innate method present in all ruby objects ie object_id method.我对所有 ruby​​ 对象中存在的一种先天方法(即 object_id 方法)的工作感到困惑。 When I run object_id method on any Fixnum object again and again, for example in irb if I do this,当我一次又一次地在任何 Fixnum 对象上运行 object_id 方法时,例如在 irb 中,如果我这样做,

>>100.object_id >>100.object_id
=>201 =>201

and do this again,然后再做一次

>>100.object_id >>100.object_id
=>201 =>201

But when I work with String object for example但是当我使用 String 对象时

>>"Hello".object_id >>“你好”.object_id
=>162333336 =>162333336

and do this again,然后再做一次

>>"Hello".object_id >>“你好”.object_id
=>15502236 =>15502236

Why so?为什么这样? In ruby, everything is an object, and every object has an innate method named object_id which uniquely identifies the object.在 ruby​​ 中,一切都是对象,每个对象都有一个名为 object_id 的固有方法,该方法唯一标识该对象。 But here, ruby is confusing me as it treats two strings with same text (ie "Hello") as different, but two Fixnum objects with same value (ie100) as the same and gives the same object id for them.但是在这里,ruby 使我感到困惑,因为它将具有相同文本(即“Hello”)的两个字符串视为不同的字符串,但将具有相同值(即 100)的两个 Fixnum 对象视为相同并为它们提供相同的对象 ID。 Why so?为什么这样? Can any one please help me?谁能帮帮我吗?

Fixnums are immutable objects in Ruby. Fixnum 是 Ruby 中的不可变对象。 There is exactly one instance created and you work with that object "directly".只创建了一个实例,您可以“直接”使用该对象。 ie references are not used unlike other regular objects.即不像其他常规对象那样使用引用。 So They have a fixed object_id.所以他们有一个固定的object_id。 This is ok because you have only one instance of the object.这是可以的,因为您只有一个对象实例。

But when you write "hello", a new string object is created.但是当你写“hello”时,会创建一个新的字符串对象。 And in the same script, if you give another "hello", even though they have same content, a new object is created.并且在同一个脚本中,如果你再给出一个“你好”,即使它们的内容相同,也会创建一个新对象。 Hence the different object_ids.因此不同的object_ids。

Such behaviour is a matter of Ruby implementation, not specification.这种行为是 Ruby 实现的问题,而不是规范的问题。 Most likely, you're using MRI (compiled from C source), in JRuby you can get different results.最有可能的是,您正在使用 MRI(从 C 源代码编译),在 JRuby 中您可以获得不同的结果。

For performance purposes, MRI handles true , false , nil , Fixnum and symbol specially.出于性能目的,MRI 专门处理truefalsenilFixnumsymbol A couple of links where you can find more info about it: http://www.oreillynet.com/ruby/blog/2006/02/ruby_values_and_object_ids.html , http://rhg.rubyforge.org/chapter02.html几个链接,您可以在其中找到有关它的更多信息: http : //www.oreillynet.com/ruby/blog/2006/02/ruby_values_and_object_ids.html,http ://rhg.rubyforge.org/chapter02.html

如果您想获得字符串的相同对象 id,您必须先将其转换为符号,然后您的 object_id 保持不变

'Hello'.to_sym.object_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM