0
0
Rubyprogramming~20 mins

Hash creation with symbols and strings in Ruby - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ruby Hash Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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"]
Anil\nnil
BAlice\n
C30\nAlice
DAlice\n30
Attempts:
2 left
💡 Hint
Remember that symbol keys and string keys are different in Ruby hashes.
Predict Output
intermediate
2: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"]
ABob\nCarol
BCarol\nBob
CBob\nBob
DCarol\nCarol
Attempts:
2 left
💡 Hint
Check how Ruby treats symbol keys and string keys separately.
🔧 Debug
advanced
2: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"]
ABecause "city" is not a valid key type
BBecause the hash is empty
CBecause :city and "city" are different keys in Ruby hashes
DBecause the hash keys must be strings only
Attempts:
2 left
💡 Hint
Think about the difference between symbols and strings as keys.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in hash creation
Which option contains a syntax error when creating a Ruby hash with symbol and string keys?
Ah = { a: 1, "b" => 2 }
Bh = { :a: 1, "b" => 2 }
Ch = { :a => 1, "b" => 2 }
Dh = { a: 1, b: 2 }
Attempts:
2 left
💡 Hint
Check the correct syntax for symbol keys in hashes.
🚀 Application
expert
3:00remaining
Count keys by type in a mixed hash
Given this Ruby hash:
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}"
ASymbols: 2, Strings: 2
BSymbols: 3, Strings: 1
CSymbols: 0, Strings: 4
DSymbols: 4, Strings: 0
Attempts:
2 left
💡 Hint
Look carefully at the keys and their types.