Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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
20,999 Points

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