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 trialPhilip Benton
1,378 PointsWhat is the difference between having the : at the beginning or end of a Ruby symbol?
I'm just working through some of the Active Record videos and keep getting confused between the : being at the beginning or end of a Ruby symbol.
Can someone enlighten me as to the difference and use cases?
2 Answers
Andrew Olson
4,028 PointsHi Phillip!
Using the :
at the end of a symbol is usually reserved for specifying a hash key.
Something like:
{
username: 'jane',
number_of_logins: 2,
favorite_color: 'blue'
}
Using the :
at the beginning of the symbol is usually used for assigning a value.
Something like:
favorite_color = :blue
You can also combine the two:
{
favorite_color: :blue
}
Hope this helps.
Philip Benton
1,378 PointsHey Andrew, that's a great help thanks.
Are both cases still classed as symbols?
Andrew Olson
4,028 PointsExactly, they're both just symbols.
Try it out with irb
:
irb(main):001:0> hash = { favorite_color: :blue }
=> {:favorite_color=>:blue}
irb(main):002:0> hash.keys.first.class
=> Symbol
irb(main):003:0> hash.values.first.class
=> Symbol