1

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.

Community
  • 1
  • 1
Filip Bartuzi
  • 5,711
  • 7
  • 54
  • 102
  • I think a better question would be. "What is the method used by Ruby to compute the `object_id` of an object?" needless to say that if every time you run Ruby the `object_id` of an specific object changes, it's because something is changing. Because nothing changed you can expect the same object_id in the same platform for an specific object. – yeyo Apr 05 '15 at 16:13
  • I didn't approach problem from this point of view! Nice tip :) – Filip Bartuzi Apr 05 '15 at 16:17
  • 2
    possible duplicate of http://stackoverflow.com/questions/3430280/how-does-object-id-assignment-work – archit gupta Apr 05 '15 at 17:33
  • @architgupta answers don't say anything about symbols. I found there answer only to the first part of my question – Filip Bartuzi Apr 05 '15 at 18:30
  • I am digging deeper :) – archit gupta Apr 05 '15 at 19:19

2 Answers2

3

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

Community
  • 1
  • 1
archit gupta
  • 954
  • 10
  • 13
-1

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
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
  • `It's also worth noting that every whole number will have same object_id as opposed to other data types.` - that's false. False/True/Nil have always the same id – Filip Bartuzi Apr 05 '15 at 16:18