Hash creation with symbols and strings in Ruby - Time & Space Complexity
We want to understand how long it takes to create a hash with symbols and strings as keys.
How does the time needed change when the hash gets bigger?
Analyze the time complexity of the following code snippet.
hash = {}
keys = [:a, :b, :c, :d, :e]
values = [1, 2, 3, 4, 5]
keys.each_with_index do |key, i|
hash[key] = values[i]
hash[key.to_s] = values[i] * 10
end
This code creates a hash and adds pairs with symbol keys and string keys.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over the keys array to add entries to the hash.
- How many times: Once for each key in the keys array.
Each key causes two insertions into the hash, so the work grows as the number of keys grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 insertions |
| 100 | 200 insertions |
| 1000 | 2000 insertions |
Pattern observation: The number of operations grows directly with the number of keys.
Time Complexity: O(n)
This means the time to create the hash grows in a straight line as you add more keys.
[X] Wrong: "Adding string keys is slower than symbol keys because strings are longer."
[OK] Correct: Both insertions happen once per key, so the time depends on the number of keys, not the key type length.
Understanding how hash creation time grows helps you write efficient code and explain your choices clearly.
"What if we changed the code to add only symbol keys? How would the time complexity change?"
Practice
Solution
Step 1: Understand symbol key syntax
In Ruby, symbol keys can be written asname: valuewithout the rocket (=>) syntax.Step 2: Check each option's syntax
{ name: "Alice", age: 30 } uses symbol keys with colon syntax correctly. { "name": "Alice", "age": 30 } uses string keys with colon, which is invalid. { :name => "Alice", "age": 30 } uses rocket syntax for the symbol key correctly but attempts colon syntax after a string key, which is invalid. { name => "Alice", age => 30 } uses bare words without colon or rocket, which is invalid.Final Answer:
{ name: "Alice", age: 30 } -> Option DQuick Check:
Symbol keys use colon syntax = { name: "Alice", age: 30 } [OK]
- Using quotes around symbol keys with colon syntax
- Omitting colon or rocket for keys
- Mixing string and symbol keys without proper syntax
Solution
Step 1: Review valid key syntax
Symbol keys can be written as:name =>orname:. String keys must be quoted and use rocket syntax.Step 2: Identify invalid syntax
{ name => "Bob", age => 25 } uses bare words as keys without colon or rocket, which is invalid and causes syntax error.Final Answer:
SyntaxError -> Option AQuick Check:
Bare words as keys need colon or rocket [OK]
- Using bare words as keys without colon or rocket
- Mixing string keys without quotes
- Confusing colon placement for symbols
person = { name: "Carol", "age" => 28 }
puts person[:name]
puts person["age"]Solution
Step 1: Understand hash keys and access
The hash has a symbol key:nameand a string key"age". Accessing with matching key types returns values.Step 2: Evaluate each puts statement
person[:name]returns "Carol".person["age"]returns 28. Both print on separate lines.Final Answer:
Carol 28 -> Option AQuick Check:
Match key types to get values = Carol 28 [OK]
- Accessing string key with symbol or vice versa
- Expecting mixed keys to be interchangeable
- Forgetting keys are type-sensitive
data = { :city => "Paris", country: "France", "population" => 2148327, state } Solution
Step 1: Check each key-value pair
Keys :city, country, and "population" have values. The key 'state' is written without a value, which is invalid.Step 2: Identify syntax error
Every key in a hash must have a corresponding value. Missing value for 'state' causes syntax error.Final Answer:
Missing value for key 'state' -> Option CQuick Check:
All keys need values in hash = Missing value for key 'state' [OK]
- Leaving keys without values
- Confusing symbol and string key syntax
- Assuming mixed keys cause errors
arr = [["name", "Dave"], [:age, 40], ["city", "NY"]], which code correctly converts it into a hash with symbol keys where possible?Solution
Step 1: Understand the array structure
The array has pairs with keys as strings or symbols. We want all keys as symbols where possible.Step 2: Convert keys to symbols
hash = arr.map { |k, v| [k.to_sym, v] }.to_h converts each key to symbol usingk.to_symbefore creating the hash, ensuring keys are symbols.Step 3: Check other options
hash = arr.to_h keeps keys as is (mixed). hash = arr.map { |k, v| [k, v] }.to_h keeps keys as is without conversion. hash = arr.map { |k, v| [k.to_s, v] }.to_h converts all keys to strings, not symbols.Final Answer:
hash = arr.map { |k, v| [k.to_sym, v] }.to_h -> Option BQuick Check:
Useto_symon keys to get symbol keys [OK]
- Not converting string keys to symbols
- Using to_s instead of to_sym
- Assuming to_h converts keys automatically
Ready to prove it?
Pass the test and this pattern moves unknown
