Why blocks are fundamental to Ruby - Performance Analysis
Blocks in Ruby let us repeat actions or pass chunks of code to methods. Understanding their time cost helps us see how programs grow when using blocks.
We want to know how the number of steps changes as the block runs more times.
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 runs the block to print double the number.
- Primary operation: The block runs once for each item in the array.
- How many times: Exactly as many times as there are items in the array.
Each extra item means one more block run, so the steps grow evenly with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 block runs |
| 100 | 100 block runs |
| 1000 | 1000 block runs |
Pattern observation: The work grows straight with the number of items.
Time Complexity: O(n)
This means the time to run the block grows directly with the number of items.
[X] Wrong: "Blocks run instantly and don't add to time."
[OK] Correct: Each block run takes time, so more items mean more total time.
Knowing how blocks affect time helps you explain how Ruby handles repeated actions clearly and confidently.
"What if the block itself contained another loop over the array? How would the time complexity change?"