0
0
Rubyprogramming~5 mins

Method overriding in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method overriding
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code changes when we use method overriding in Ruby.

Specifically, we ask: does overriding a method affect how long the program runs as input grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Animal
  def speak
    "Hello"
  end
end

class Dog < Animal
  def speak
    "Woof!"  # Overrides Animal's speak
  end
end

animals = [Animal.new, Dog.new, Animal.new]
animals.each { |a| puts a.speak }

This code defines a base class and a subclass that overrides a method. It then calls the method on a list of objects.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array of objects and calling speak on each.
  • How many times: Once for each object in the array (3 times here, but could be more).
How Execution Grows With Input

Each object in the list has its speak method called once. As the list grows, the number of calls grows the same way.

Input Size (n)Approx. Operations
1010 method calls
100100 method calls
10001000 method calls

Pattern observation: The number of method calls grows directly with the number of objects.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of objects we call the method on.

Common Mistake

[X] Wrong: "Overriding a method makes the program slower because it adds extra work."

[OK] Correct: Overriding just changes which code runs, but calling the method still happens once per object, so the time grows the same way.

Interview Connect

Understanding how method overriding affects performance helps you explain your code choices clearly and shows you know how programs run as they grow.

Self-Check

What if the speak method called another method inside it that loops over a list? How would the time complexity change?