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

Jon Hockley
Jon Hockley
3,781 Points

Ruby Hash Exra Credit

Hi guys,

I've had a stab at the extra credit for the hash badge, but my block seems to be running but not converting my string keys to symbols.

Can anyone point me in the right direction? I know I could probably find an answer online, but I'd rather be told what my code is (or isn't) doing.

Here's what I have:

mlc = Hash.new
mlc['business_name'] = "Mike Leach Creative" 
mlc['location'] = "Swansea"
mlc['phone_number'] = "01792 123456"

#iterate and convert all key strings to symbols
mlc.each_key{ |k| k = k.to_sym }

puts mlc['location'].class

7 Answers

Jon Hockley
Jon Hockley
3,781 Points

Hi Andrew,

I've looked up what symbols are and understand them, I'm trying to figure out why my code isn't running. According to the docs, the .to_sym method should convert the string in the key to a symbol object?

Surely I don't just prepend my key with the : - That wouldn't change it to a symbol would it?

Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

I believe |k| k = k.to_sym is just converting the k in the block not in the dictionary.

You may need one or two more lines of code :)

Jon Hockley
Jon Hockley
3,781 Points

I've just figured that out before reading your message by putting it out in the block. I'll get back to it!

Jon Hockley
Jon Hockley
3,781 Points

I couldn't figure it out. I tried a few things but none of them worked. I'll continue with the badges and hopefully come back when I know more.

Jon Hockley
Jon Hockley
3,781 Points

Finally got it. Had to do a lot of digging around but learnt quite a bit while doing so.

If anyone else is having a bit of trouble doing this then here is my solution:

mlc = Hash.new
mlc['business_name'] = "Mike Leach Creative"
mlc['location'] = "Swansea"
mlc['phone_number'] = "01792 123456"

#map the hash to an array and create a new hash using the converted keys
mlc = Hash[mlc.map{|(k,v)| [k.to_sym,v]}]

puts mlc

Admittedly I found this on StackOverflow, but it was a good learning experience to break it all down and work out what is actually happening. I originally assigned the new hash to a new variable but ended up just re-assigning to the existing one.