Frank Zimmer
Frank Zimmer

Reputation: 51

Can't get the hang of symbols in Ruby

I have been looking the past days how to understand Symbols in Ruby. I read every article on Google about Ruby symbols, most of them are bad explanations so I come here, and I see some questions about this topic exists, however I do not understand, sorry.

From what I have read I understand that symbols are immutable and unique, so the memory consumption and performance is better than regular strings.

Question #1
Are symbols purpose in life to serve the same niche as strings? Is the purpose of symbols to function as convenient constants without carrying a value, like the part after : is it the actual value?

Question #2
When do I actually KNOW where to use symbols?

I would highly apprciate your own explanations of symbols instead of linking to articles on Google (I ensure that I already read it!).

I do also apprciate your time if you can provide more info about symbols than what I already asked about here, because I do not understand them at all, not even what is stored in :symbol_something, is it a reference or what?

Thank you very much for your help!

Upvotes: 5

Views: 252

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146073

The way to understand this is to consider that String is a Ruby object and it is not specified to be immutable. As a result, a number of optimizations are unavailable to the language processor and a reader of the code may or may not understand whether a given string is functioning as a mutable data structure or as the key to something.

But symbols are immutable, so they have unique instances. They are also easy to type, and the use of a symbol clearly indicates "identifier" or "token" to anyone reading the code later.

Finally, class Symbol implements the explicit conversion #to_s, so symbols are safe to use in expressions where you know #to_s will be called, such as in ERB templates or in I/O operations.

Upvotes: 1

ennuikiller
ennuikiller

Reputation: 46965

symbols in ruby are a way to efficiently utilize immutable strings. For example, suppose you want to use the string "my_key" as a hash key. Simply using the string is a waste of both space and efficiency since each time you specify the hash key "my_key" you are creating a different string instance in a different memory location even though the string value contents are the same! So if you have 100 instances of my_hash['my_key'] you have 100 instance of the string 'my_key'. Not so with the symbol :my_key. There is only ever one instance of :my_key no matter how many times you utilize it!

You should use symbols where you would normally uses an immutable string as an identifier.

Upvotes: 6

Related Questions