Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.