Reputation: 5931
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
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:
Upvotes: 3
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