Local variables and naming conventions in Ruby - Time & Space Complexity
We want to see how the way we name and use local variables affects how long a program takes to run.
Does choosing different names or using many local variables change the speed?
Analyze the time complexity of the following code snippet.
def sum_array(numbers)
total = 0
numbers.each do |num|
total += num
end
total
end
This code adds up all numbers in an array using a local variable named total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array.
- How many times: Once for every item in the array.
As the array gets bigger, the program does more additions, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the input size grows.
[X] Wrong: "Using longer or more descriptive variable names will slow down the program."
[OK] Correct: Variable names are only for humans reading the code; the computer runs at the same speed regardless of name length.
Understanding that naming variables well helps people, not the computer, shows you care about clear code and good teamwork.
"What if we replaced the loop with a built-in method like sum? How would the time complexity change?"