Understanding Symbols In Ruby

Posted by Kezzer on Stack Overflow See other posts from Stack Overflow or by Kezzer
Published on 2010-02-26T13:22:05Z Indexed on 2010/06/08 23:42 UTC
Read the original article Hit count: 280

Filed under:
|

Despite reading this article, I'm still confused as to the representation of the data in memory when it comes to using symbols. If a symbol, two of them contained in different objects, exist in the same memory location, then how is it that they contain different values? I'd have expected the same memory location to contain the same value. As a quote from the link:

Unlike strings, symbols of the same name are initialized and exist in memory only once during a session of ruby

I just don't understand how it manages to differentiate the values contained in the same memory location.


EDIT

So let's consider the example:

patient1 = { :ruby => "red" }
patient2 = { :ruby => "programming" }

patient1.each_key {|key| puts key.object_id.to_s}
3918094
patient2.each_key {|key| puts key.object_id.to_s}
3918094

patient1 and patient2 are both hashes, that's fine. :ruby however is a symbol. If we were to output the following:

patient1.each_key {|key| puts key.to_s}

Then what will be output? "red", or "programming"?


FURTHER EDIT

I'm still really quite confused. I'm thinking a symbol is a pointer to a value. Let's forget hashes for a second. The questions I have are; can you assign a value to a symbol? Is a symbol just a pointer to a variable with a value in it? If symbols are global, does that mean a symbol always points to one thing?

© Stack Overflow or respective owner

Related posts about ruby

Related posts about symbols