0
0
Rubyprogramming~20 mins

Symbol keys vs string keys decision in Ruby - Practice Questions

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Symbol Key Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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']
A
bar

B
bar

nil
C
nil
bar
D
nil
nil
Attempts:
2 left
💡 Hint
Remember that symbol keys and string keys are different in Ruby hashes.
🧠 Conceptual
intermediate
2: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?
ASymbols are immutable and reused, saving memory compared to strings.
BSymbols are mutable and can be changed at runtime.
CSymbols automatically convert to strings when used as keys.
DSymbols allow faster string concatenation.
Attempts:
2 left
💡 Hint
Think about memory and performance when using symbols as keys.
Predict Output
advanced
2: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!']
A
Alice

nil
B
nil

Alice
C
nil

nil
D
Alice

Alice
Attempts:
2 left
💡 Hint
Consider what happens when you mutate the string used as a key after the hash is created.
🔧 Debug
advanced
2:00remaining
Why does this hash key lookup fail?
Given this code, why does h[:name] return nil?
Ruby
h = { 'name' => 'Bob' }
puts h[:name]
ABecause the key :name is misspelled.
BBecause the hash key is a symbol, but lookup uses a string key.
CBecause the hash is empty.
DBecause the hash key is a string, but lookup uses a symbol key.
Attempts:
2 left
💡 Hint
Check the type of the key used when creating the hash and when accessing it.
🚀 Application
expert
3: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 }
A1
B3
C2
D4
Attempts:
2 left
💡 Hint
Look carefully at each key's type: symbol or string.