Open struct for dynamic objects in Ruby - Time & Space Complexity
When using open structs in Ruby, we create objects that can have properties added on the fly.
We want to understand how the time to access or add these properties changes as the object grows.
Analyze the time complexity of the following Ruby code using OpenStruct.
require 'ostruct'
obj = OpenStruct.new
100.times do |i|
obj["key_#{i}"] = i
end
value = obj.key_50
This code creates an OpenStruct object, adds 100 dynamic properties, then accesses one property.
Look at what repeats and what takes time.
- Primary operation: Adding properties inside a loop (100 times).
- How many times: Each property is added once, so 100 times.
- Accessing a property happens once at the end.
- The dominant cost is adding properties because it happens many times.
Adding more properties means more work each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 property additions |
| 100 | About 100 property additions |
| 1000 | About 1000 property additions |
Pattern observation: The work grows roughly in direct proportion to how many properties you add.
Time Complexity: O(n)
This means the time to add properties grows linearly as you add more properties.
[X] Wrong: "Accessing a property in OpenStruct is always instant, no matter how many properties there are."
[OK] Correct: OpenStruct stores properties internally in a hash, so access is fast, but adding many properties still takes time proportional to how many you add.
Understanding how dynamic objects like OpenStruct work helps you reason about performance in flexible code.
This skill shows you can think about how your code behaves as it grows, which is valuable in many programming tasks.
"What if we changed OpenStruct to a plain Ruby hash? How would the time complexity for adding and accessing properties change?"