0
0
Rubyprogramming~5 mins

Module methods in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Module methods
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: The method uses map to go through each number once.
  • How many times: It runs once for each number in the input array.
How Execution Grows With Input

As the input array gets bigger, the method does more work, one step per number.

Input Size (n)Approx. Operations
1010
100100
10001000

Pattern observation: The work grows directly with the number of items; doubling items doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the input size.

Common Mistake

[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.

Interview Connect

Understanding how module methods handle input size helps you explain code efficiency clearly and confidently.

Self-Check

What if the method used nested loops inside the module method? How would the time complexity change?