Ruby Ruby Collections Ruby Hashes Ruby Hash Creation

lindseyk
lindseyk
4,506 Points

Coming from first learning Python, the concept of a "symbol" is confusing to me. Can someone clarify?

I'm confused about what exactly a symbol is and why they are used. Also, the fact that a key can be either key: or :key. Can someone explain to me the difference between syntax for dictionaries in Python vs. hashes in Ruby? Just trying to wrap my head around this. Thanks!!

2 Answers

Esbjörn Stenberg
Esbjörn Stenberg
7,420 Points

Hi Lindseyk

Symbols is a variable type, just like strings and numbers. The big difference is that a symbol will always be the same symbol in memory. A string will always be a different string in memory.

Example:

STest1 = "Test"
STest2 = "Test"
STest3 = "Test"

puts STest1.object_id      #=> 47390561511060
puts STest2.object_id      #=> 47390561511020
puts STest3.object_id      #=> 47390561511000

#Same test with symbols

SymTest1 = :Test
SymTest2 = :Test
SymTest3 = :Test

puts SymTest1.object_id     #=> 906148
puts SymTest2.object_id     #=> 906148
puts SymTest3.object_id     #=> 906148

All strings look the same while written, however they are completly different in memory. The symbols is though the same in both memory and in the code.

The symbol syntax of putting the colons behind the symbol is a feature in hashes. Instead of writing a symbol and a hash rocket (=>) you can just write the colon at the end of the symbol.

{:test => "This is a test"}
    #Can also be written as
{test: "This is a test"}

I hope this will help you, if you still has the problem ofcourse!

valeriuv
valeriuv
17,087 Points

That's a good explanation of what symbols are. Could you also clarify what use cases they have? Why do we need them?