Ruby style guide essentials - Time & Space Complexity
When writing Ruby code, following a style guide helps keep code clean and easy to read.
We want to understand how the style choices affect the time it takes for code to run.
Analyze the time complexity of this Ruby method that formats and prints names.
def print_names(names)
names.each do |name|
formatted = name.strip.capitalize
puts formatted
end
end
This code goes through a list of names, cleans and formats each, then prints it.
Look for loops or repeated actions.
- Primary operation: Looping through each name in the list.
- How many times: Once for every name in the input list.
As the list of names gets bigger, the work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 formatting and printing steps |
| 100 | About 100 formatting and printing steps |
| 1000 | About 1000 formatting and printing steps |
Pattern observation: The work grows evenly as the list grows; double the names, double the work.
Time Complexity: O(n)
This means the time to finish grows directly with the number of names.
[X] Wrong: "Formatting each name is a fixed small cost, so time stays the same no matter how many names."
[OK] Correct: Each name needs its own formatting step, so more names mean more work.
Understanding how simple loops affect time helps you explain your code clearly and think about efficiency in real projects.
"What if we added a nested loop inside to compare each name with every other name? How would the time complexity change?"