Challenge - 5 Problems
Ruby Hash Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a hash with mixed keys
What is the output of this Ruby code?
h = { :name => "Alice", "age" => 30 }
puts h[:name]
puts h["age"]Ruby
h = { :name => "Alice", "age" => 30 }
puts h[:name]
puts h["age"]Attempts:
2 left
💡 Hint
Remember that symbol keys and string keys are different in Ruby hashes.
✗ Incorrect
In Ruby, :name and "name" are different keys. The hash has :name and "age" keys. So h[:name] returns "Alice" and h["age"] returns 30.
❓ Predict Output
intermediate2:00remaining
Hash key lookup with symbol vs string
What will this Ruby code output?
h = { name: "Bob", "name" => "Carol" }
puts h[:name]
puts h["name"]Ruby
h = { name: "Bob", "name" => "Carol" }
puts h[:name]
puts h["name"]Attempts:
2 left
💡 Hint
Check how Ruby treats symbol keys and string keys separately.
✗ Incorrect
The hash has two keys: :name and "name". They are different keys with different values. So h[:name] returns "Bob" and h["name"] returns "Carol".
🔧 Debug
advanced2:00remaining
Why does this hash key lookup fail?
This Ruby code returns nil for the second puts. Why?
h = { :city => "Paris" }
puts h["city"]Ruby
h = { :city => "Paris" }
puts h["city"]Attempts:
2 left
💡 Hint
Think about the difference between symbols and strings as keys.
✗ Incorrect
In Ruby, symbol keys and string keys are distinct. The hash has :city key but no "city" key, so h["city"] returns nil.
📝 Syntax
advanced2:00remaining
Identify the syntax error in hash creation
Which option contains a syntax error when creating a Ruby hash with symbol and string keys?
Attempts:
2 left
💡 Hint
Check the correct syntax for symbol keys in hashes.
✗ Incorrect
Option B uses :a: which is invalid syntax. The correct symbol key syntax is either :a => 1 or a: 1.
🚀 Application
expert3:00remaining
Count keys by type in a mixed hash
Given this Ruby hash:
How many keys are symbols and how many are strings?
h = { name: "Eve", "age" => 28, city: "NY", "country" => "USA" }How many keys are symbols and how many are strings?
Ruby
h = { name: "Eve", "age" => 28, city: "NY", "country" => "USA" }
symbol_count = h.keys.count { |k| k.is_a?(Symbol) }
string_count = h.keys.count { |k| k.is_a?(String) }
puts "Symbols: #{symbol_count}, Strings: #{string_count}"Attempts:
2 left
💡 Hint
Look carefully at the keys and their types.
✗ Incorrect
The hash has keys :name and :city as symbols, and "age" and "country" as strings, so 2 symbols and 2 strings.