Challenge - 5 Problems
Symbol Key Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of hash key access with symbol vs string
What is the output of this Ruby code?
Ruby
h = { foo: 'bar' }
puts h[:foo]
puts h['foo']Attempts:
2 left
💡 Hint
Remember that symbol keys and string keys are different in Ruby hashes.
✗ Incorrect
In Ruby, a hash with symbol keys does not recognize string keys as the same. So h[:foo] returns 'bar', but h['foo'] returns nil.
🧠 Conceptual
intermediate2:00remaining
Why choose symbol keys over string keys?
Which of the following is the main reason to prefer symbol keys over string keys in Ruby hashes?
Attempts:
2 left
💡 Hint
Think about memory and performance when using symbols as keys.
✗ Incorrect
Symbols are immutable and reused internally, so using them as hash keys saves memory and can improve performance compared to strings.
❓ Predict Output
advanced2:00remaining
Effect of string keys mutation on hash keys
What is the output of this Ruby code?
Ruby
key = 'name' h = { key => 'Alice' } key << '!' puts h['name'] puts h['name!']
Attempts:
2 left
💡 Hint
Consider what happens when you mutate the string used as a key after the hash is created.
✗ Incorrect
The hash key is the original string 'name'. Mutating the string variable after adding it as a key does not change the existing key in the hash. So h['name'] returns 'Alice', but h['name!'] returns nil.
🔧 Debug
advanced2:00remaining
Why does this hash key lookup fail?
Given this code, why does
h[:name] return nil?Ruby
h = { 'name' => 'Bob' }
puts h[:name]Attempts:
2 left
💡 Hint
Check the type of the key used when creating the hash and when accessing it.
✗ Incorrect
The hash key is the string 'name', but the lookup uses the symbol :name. These are different keys in Ruby hashes, so h[:name] returns nil.
🚀 Application
expert3:00remaining
Count keys that are symbols in a mixed hash
Given this hash, how many keys are symbols?
Ruby
h = { foo: 1, 'bar' => 2, :baz => 3, 'qux' => 4 }Attempts:
2 left
💡 Hint
Look carefully at each key's type: symbol or string.
✗ Incorrect
The keys foo: and :baz are symbols. The keys 'bar' and 'qux' are strings. So there are 2 symbol keys.