Self keyword behavior in Ruby - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Looping
ntimes with@n.times. - How many times: The
print_numbermethod is called once per loop, sontimes.
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 |
|---|---|
| 10 | About 10 method calls and prints |
| 100 | About 100 method calls and prints |
| 1000 | About 1000 method calls and prints |
Pattern observation: The work grows evenly as n grows; doubling n doubles the work.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the size of n.
[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.
Understanding how method calls inside loops affect time helps you explain code efficiency clearly and confidently in interviews.
"What if we replaced self.print_number(i) with just print_number(i)? How would the time complexity change?"