0
0
Rubyprogramming~5 mins

Open struct for dynamic objects in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Open struct for dynamic objects
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Adding more properties means more work each time.

Input Size (n)Approx. Operations
10About 10 property additions
100About 100 property additions
1000About 1000 property additions

Pattern observation: The work grows roughly in direct proportion to how many properties you add.

Final Time Complexity

Time Complexity: O(n)

This means the time to add properties grows linearly as you add more properties.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we changed OpenStruct to a plain Ruby hash? How would the time complexity for adding and accessing properties change?"