简体   繁体   中英

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. When I run object_id method on any Fixnum object again and again, for example in irb if I do this,

>>100.object_id
=>201

and do this again,

>>100.object_id
=>201

But when I work with String object for example

>>"Hello".object_id
=>162333336

and do this again,

>>"Hello".object_id
=>15502236

Why so? In ruby, everything is an object, and every object has an innate method named object_id which uniquely identifies the object. 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. Why so? Can any one please help me?

Fixnums are immutable objects in 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. This is ok because you have only one instance of the object.

But when you write "hello", a new string object is created. 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.

Such behaviour is a matter of Ruby implementation, not specification. Most likely, you're using MRI (compiled from C source), in JRuby you can get different results.

For performance purposes, MRI handles true , false , nil , Fixnum and symbol specially. 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

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

'Hello'.to_sym.object_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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