Class methods with self prefix in Ruby - Time & Space Complexity
We want to understand how long a class method with the self prefix takes to run as the input size grows.
How does the work inside such a method change when we give it bigger input?
Analyze the time complexity of the following code snippet.
class Calculator
def self.sum(numbers)
total = 0
numbers.each do |num|
total += num
end
total
end
end
This method adds up all numbers in an array and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every number in the input array.
As the list of numbers gets bigger, the method does more additions, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Class methods with self run instantly no matter the input size."
[OK] Correct: Even though it's a class method, if it loops through input, the time depends on how big the input is.
Knowing how class methods scale with input size helps you explain your code clearly and shows you understand efficiency.
"What if we changed the method to call itself recursively for each number? How would the time complexity change?"
Practice
self. before a method name inside a Ruby class do?Solution
Step 1: Understand the role of
In Ruby, prefixing a method name withself.in method definitionself.inside a class defines it as a class method.Step 2: Identify how class methods are called
Class methods are called on the class itself, not on instances of the class.Final Answer:
Makes the method a class method, callable on the class itself -> Option DQuick Check:
self.method_namedefines class method [OK]
- Thinking self. makes method private
- Confusing class methods with instance methods
- Assuming self. methods are only for internal use
greet inside a Ruby class?Solution
Step 1: Recall class method syntax
Class methods in Ruby are defined by prefixing the method name withself.inside the class.Step 2: Check each option
def self.greet; puts 'Hello'; end usesdef self.greet, which is the correct syntax for a class method.Final Answer:
def self.greet; puts 'Hello'; end -> Option CQuick Check:
Class method syntax = def self.method_name [OK]
- Omitting self. for class methods
- Using instance variable syntax (@) for methods
- Trying to use :: inside method definition
class Calculator
def self.add(a, b)
a + b
end
end
puts Calculator.add(3, 4)Solution
Step 1: Identify the method type and call
The methodaddis defined as a class method usingself.add, so it can be called on the class Calculator.Step 2: Evaluate the method call
CallingCalculator.add(3, 4)returns the sum of 3 and 4, which is 7.Final Answer:
7 -> Option AQuick Check:
Class method call returns sum 7 [OK]
- Trying to call add on an instance
- Confusing string concatenation with addition
- Expecting error due to method definition
class Person
def self.say_hello
puts "Hello!"
end
def self.say_goodbye
puts "Goodbye!"
end
def say_hello
puts "Hi!"
end
end
Person.say_hello
Person.say_goodbye
Person.new.say_hello
Person.say_hello()Solution
Step 1: Analyze method definitions
There are two class methodsself.say_helloandself.say_goodbye, and one instance methodsay_hello.Step 2: Check method calls
CallingPerson.say_hellocalls the class method.Person.new.say_hellocalls the instance method. Parentheses inPerson.say_hello()are allowed in Ruby.Final Answer:
No error, all calls are valid -> Option BQuick Check:
Class and instance methods coexist without conflict [OK]
- Assuming parentheses cause errors in method calls
- Thinking class and instance methods with same name conflict
- Expecting error when calling class method with parentheses
Counter that keeps track of how many times its class method increment is called. Which code correctly implements this behavior?Solution
Step 1: Understand class variable vs class instance variable
Using@@countis a class variable shared across subclasses, but@countinside class methods is a class instance variable, safer for this use.Step 2: Check method definitions
class Counter def self.increment @count ||= 0 @count += 1 end def self.count @count end end uses@count ||= 0inside the class method to initialize the class instance variable, then increments it. It also provides a class methodcountto read the value.Final Answer:
class Counter def self.increment @count ||= 0 @count += 1 end def self.count @count end end -> Option AQuick Check:
Use class instance variable @count inside self methods [OK]
- Using instance methods to change class state
- Using @@count without initialization causing errors
- Confusing instance variables with class variables
Ready to prove it?
Pass the test and this pattern moves unknown
