Block syntax (do..end and curly braces) in Ruby - Time & Space Complexity
When using blocks in Ruby, it's important to see how the code inside runs as input grows.
We want to know how the number of times the block runs changes with input size.
Analyze the time complexity of the following code snippet.
numbers = [1, 2, 3, 4, 5]
numbers.each do |num|
puts num * 2
end
This code goes through each number in the list and prints double its value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The block inside
eachruns once for every item in the array. - How many times: Exactly as many times as there are elements in the array.
As the list gets bigger, the block runs more times, directly matching the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 block executions |
| 100 | 100 block executions |
| 1000 | 1000 block executions |
Pattern observation: The number of operations grows in a straight line with input size.
Time Complexity: O(n)
This means the time to run grows directly with how many items are in the list.
[X] Wrong: "Using curly braces instead of do..end changes how many times the block runs."
[OK] Correct: Both block styles run the same number of times; the difference is only in syntax and precedence, not performance.
Understanding how blocks run helps you explain how your code scales and shows you know how Ruby handles repeated actions.
"What if we replaced each with map? How would the time complexity change?"