0
0
Rubyprogramming~5 mins

Method declaration with def in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Method declaration with def
O(n)
Understanding Time Complexity

When we declare a method using def in Ruby, it is important to understand how the time it takes to run grows as the method does more work.

We want to know how the number of steps changes when the method handles bigger inputs.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def greet(names)
  names.each do |name|
    puts "Hello, #{name}!"
  end
end

names_list = ["Alice", "Bob", "Charlie"]
greet(names_list)

This method takes a list of names and prints a greeting for each name.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each name in the list with each.
  • How many times: Once for every name in the list.
How Execution Grows With Input

As the list of names gets bigger, the method runs the greeting for each name.

Input Size (n)Approx. Operations
1010 greetings printed
100100 greetings printed
10001000 greetings printed

Pattern observation: The number of greetings grows directly with the number of names.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of names.

Common Mistake

[X] Wrong: "Declaring a method with def always takes constant time no matter what happens inside."

[OK] Correct: The time depends on what the method does. If it loops over input, the time grows with input size.

Interview Connect

Understanding how method declarations relate to time helps you explain how your code behaves as inputs grow, a key skill in programming.

Self-Check

"What if the method called another method inside the loop? How would the time complexity change?"