Filip Bartuzi
Filip Bartuzi

Reputation: 5931

object_id of keys (and some other objects) are always the same. Why is that?

In every Ruby program Symbol :x (where x is any characters sequence allowed to be used as a name for a Symbol) has the same object_id.

The same thing is with false/true/nil.

I wonder - why is that? Does it mean that every time Ruby initialise all these objects before code is executed (like false/true/nil)? <--- Already answered here: How does object_id assignment work?

And what about Symbols? Are these initialised also? A millions of possible combinations? How is it possible that their .object_id are the same between programs.

Upvotes: 1

Views: 327

Answers (2)

archit gupta
archit gupta

Reputation: 1034

So i searched over the internet and found out this article http://threebrothers.org/brendan/blog/memory-and-ruby-symbols/ . I come to know that ruby process maintains a symbol table which has one entry per symbol as long as the process exists, so whenever a new symbol is created ruby do a search in that symbol table and if not exists it creates a new one to the last entry just like the entries in database tables.

More sources that can help:

Id2sym & symbol.object_id

Upvotes: 3

Amit Joki
Amit Joki

Reputation: 59262

From the "The Book Of Ruby"

A symbol is, in fact, a pointer into the symbol table. The symbol table is Ruby’s internal list of known identifiers – such as variable and method names.

A Symbol is efficient as keys, as there can't be instances of it. It's like a constant.

It's also worth noting that every whole number will have same object_id as opposed to types like String. Boolean, FixNum, nil have the same object_id

"Iamnotefficentasakey".object_id #=> Different here 
"Iamnotefficentasakey".object_id #=> Different here
:iam.object_id #=> Same here
:iam.object_id #=> Same here

Upvotes: -1

Related Questions