Method declaration with def in Ruby - Time & Space 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.
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 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.
As the list of names gets bigger, the method runs the greeting for each name.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greetings printed |
| 100 | 100 greetings printed |
| 1000 | 1000 greetings printed |
Pattern observation: The number of greetings grows directly with the number of names.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of names.
[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.
Understanding how method declarations relate to time helps you explain how your code behaves as inputs grow, a key skill in programming.
"What if the method called another method inside the loop? How would the time complexity change?"