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?"
Practice
self keyword represent inside an instance method in Ruby?Solution
Step 1: Understand instance methods context
Inside an instance method, the code runs for a specific object created from the class.Step 2: Identify what
In this context,selfpoints toselfrefers to that specific object (instance) running the method.Final Answer:
The current instance (object) of the class -> Option DQuick Check:
selfin instance method = instance [OK]
- Confusing self with the class inside instance methods
- Thinking self is a global or class variable
- Assuming self is always the class
self in Ruby?Solution
Step 1: Recall class method syntax
Class methods are defined by prefixing the method name withself.inside the class.Step 2: Check each option's syntax
def self.my_method; 'hello'; end usesdef self.my_methodwhich is correct syntax. Others are invalid Ruby syntax.Final Answer:
def self.my_method; 'hello'; end -> Option AQuick Check:
Class method syntax = def self.method_name [OK]
- Placing self after method name
- Using colon instead of dot
- Passing self as a parameter
class Dog
def speak
self.class
end
end
fido = Dog.new
puts fido.speakSolution
Step 1: Understand what
Inside the instance methodselfis insidespeakspeak,selfis the instancefido.Step 2: Evaluate
Callingself.classclasson the instance returns its class, which isDog.Final Answer:
Dog -> Option AQuick Check:
self.classin instance method = class name [OK]
- Thinking self.class returns the instance
- Confusing class with object name
- Expecting output to be an object instead of class name
class Cat
def self.meow
puts "Meow!"
end
def meow
puts "Meow from instance"
end
def self.instance_meow
meow
end
end
Cat.instance_meowSolution
Step 1: Analyze method calls inside
This is a class method trying to callself.instance_meowmeowwithout specifying an instance.Step 2: Understand method types
meowwithoutself.is an instance method, so it needs an object to call it on.Step 3: Identify the error
Calling an instance method directly inside a class method causes a NoMethodError because no instance is given.Final Answer:
Calling instance methodmeowinside a class method without an instance -> Option BQuick Check:
Class methods cannot call instance methods without an object [OK]
- Trying to call instance methods directly inside class methods
- Confusing self in class vs instance methods
- Ignoring need for object to call instance methods
class Calculator
def self.description
"I am a Calculator"
end
def initialize(value)
@value = value
end
def show_description
self.class.description
end
end
calc = Calculator.new(10)
puts calc.show_descriptionSolution
Step 1: Understand
Insideself.class.descriptioninside instance methodshow_description,selfis the instancecalc. Callingclassreturns the classCalculator.Step 2: Call class method
Callingdescriptiondescriptionon the class returns the string "I am a Calculator".Final Answer:
"I am a Calculator" -> Option CQuick Check:
Instance calls class method via self.class = output string [OK]
- Expecting instance variable value instead of class method output
- Confusing self with class inside instance methods
- Thinking NoMethodError will occur
Ready to prove it?
Pass the test and this pattern moves unknown
