Parameters with default values in Ruby - Time & Space Complexity
Let's see how using default values for parameters affects how long a program takes to run.
We want to know if adding default values changes the work the program does as input grows.
Analyze the time complexity of the following code snippet.
def greet(name = "Friend")
puts "Hello, #{name}!"
end
greet("Alice")
greet()
This code defines a method that says hello to a name, or to "Friend" if no name is given.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The method runs a simple print statement once per call.
- How many times: Each call runs the print once; no loops or recursion inside.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print operations |
| 100 | 100 print operations |
| 1000 | 1000 print operations |
Pattern observation: The work grows directly with how many times the method is called, not affected by default values.
Time Complexity: O(n)
This means the time grows in a straight line with the number of calls, whether or not default values are used.
[X] Wrong: "Using default values makes the method slower because it has to check the defaults every time."
[OK] Correct: The check for default values is very quick and does not add extra loops or big work, so it does not change how time grows with input size.
Understanding how default parameters affect time helps you explain your code clearly and shows you know what really matters for performance.
"What if the method had a loop inside that ran based on the parameter value? How would the time complexity change?"