0
0
Rubyprogramming~5 mins

Self keyword behavior in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Self keyword behavior
O(n)
Understanding Time Complexity

Let's explore how the use of the self keyword affects the time it takes for Ruby code to run.

We want to see how the program's work changes when calling methods with or without self.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

class Counter
  def initialize(n)
    @n = n
  end

  def count
    @n.times do |i|
      self.print_number(i)
    end
  end

  def print_number(num)
    puts num
  end
end

c = Counter.new(5)
c.count

This code counts from 0 up to n-1 and prints each number using a method called with self.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping n times with @n.times.
  • How many times: The print_number method is called once per loop, so n times.
How Execution Grows With Input

As the input n grows, the number of times the loop runs and the method calls increase directly with n.

Input Size (n)Approx. Operations
10About 10 method calls and prints
100About 100 method calls and prints
1000About 1000 method calls and prints

Pattern observation: The work grows evenly as n grows; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows in a straight line with the size of n.

Common Mistake

[X] Wrong: "Using self to call a method inside a loop makes the code slower by a lot."

[OK] Correct: Calling a method with self inside a loop does not change the overall growth pattern; it still runs once per loop, so the time grows linearly with n.

Interview Connect

Understanding how method calls inside loops affect time helps you explain code efficiency clearly and confidently in interviews.

Self-Check

"What if we replaced self.print_number(i) with just print_number(i)? How would the time complexity change?"