Block parameters in Ruby - Time & Space Complexity
When using block parameters in Ruby, it's important to see how the code runs as the input grows.
We want to know how the number of steps changes when we pass more items to the block.
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 using a block with a parameter.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
eachmethod loops over every item in the array. - How many times: Once for each item in the array, so as many times as the array length.
As the list gets bigger, the number of times the block runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times the block runs |
| 100 | 100 times the block runs |
| 1000 | 1000 times the block runs |
Pattern observation: The work grows directly with the number of items; double the items means double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items you process.
[X] Wrong: "Using a block with parameters makes the code run faster or slower than normal loops."
[OK] Correct: The block parameters just pass each item to the block; they don't change how many times the loop runs or how long it takes per item.
Understanding how blocks with parameters work helps you explain how Ruby handles repeated tasks clearly and efficiently.
"What if we replaced each with map? How would the time complexity change?"