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!

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


Gerard Comas Gual
Gerard Comas Gual
3,583 Points

Extra Credit | Symbols and hash keys.

The problema say.

Now that we know how hashes work, write a function that converts hashes with string keys in to hashes with symbols as keys. The function should work recursively.

h1 = {'key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'}

Goal h1 = {key1: value1, key2: value2, key3: value3} We can use the to_sym method like that:

h2 = Hash.new h1.each {|k, v| h2[k.to_sym] = v} h1 = h2

This approach (although works) is incorrent because we have to use a recursively function Any help?


2 Answers

Chris McKnight
Chris McKnight
11,045 Points

First, you should create a method and pass in the hash. Then create a new empty hash so you can put the new hash into it since you can't modify a hash while you are iterating it. Then, you need to loop through each key of the hash inside of the function. You will want to check if the value of the current key is a hash, hash[key].is_a? Hash. If that is true you need to call your function recursively, otherwise just call to_sym on the key and put it into the temporary hash. Finally, return the new hash.

Ria Carmin
Ria Carmin
Courses Plus Student 11,848 Points

This is my solution to the problem, but I'm pretty sure there is a better way to do it. Also, I don't really understand what a recursive function is.

  1. created a hash grades
  2. created a function symbolize and passed hash to it
  3. new hash sym_hash will be the final hash with symbols instead of strings
  4. loop through keys and values and store them in key and value
  5. put each pair of key ( key.gsub(/\s+/, "" removes white spaces; it seems like symbols cannot have white spaces, but I might be wrong) and value into sym_hash
  6. prints out sym_hash
grades = { "Jane Doe" => 10, "Jim McDonalds" => 6, "Wizzy" => nil }

def symbolize(hash)
   sym_hash = {}
   hash.each_pair do |key, value|
      sym_hash.merge!(key.gsub(/\s+/, "").intern => value)
   puts sym_hash


This is the result:

{ :JaneDoe=>10, :JimMcDonalds=>6, :Wizzy=>nil }