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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With