Module methods in Ruby - Time & Space Complexity
We want to understand how long it takes to run code that uses module methods in Ruby.
Specifically, we ask: how does the time to run change as the input grows?
Analyze the time complexity of the following code snippet.
module MathHelpers
def self.square_all(numbers)
numbers.map { |n| n * n }
end
end
n = 10
arr = (1..n).to_a
result = MathHelpers.square_all(arr)
This code defines a module method that squares each number in an array.
- Primary operation: The method uses
mapto go through each number once. - How many times: It runs once for each number in the input array.
As the input array gets bigger, the method does more work, one step per number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 |
| 100 | 100 |
| 1000 | 1000 |
Pattern observation: The work grows directly with the number of items; doubling items doubles work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "Module methods make the code run instantly, no matter the input size."
[OK] Correct: Module methods are just like regular methods; if they process each item, time grows with input size.
Understanding how module methods handle input size helps you explain code efficiency clearly and confidently.
What if the method used nested loops inside the module method? How would the time complexity change?