0
0
Rubyprogramming~5 mins

Block syntax (do..end and curly braces) in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Block syntax (do..end and curly braces)
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The block inside each runs once for every item in the array.
  • How many times: Exactly as many times as there are elements in the array.
How Execution Grows With Input

As the list gets bigger, the block runs more times, directly matching the list size.

Input Size (n)Approx. Operations
1010 block executions
100100 block executions
10001000 block executions

Pattern observation: The number of operations grows in a straight line with input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly with how many items are in the list.

Common Mistake

[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.

Interview Connect

Understanding how blocks run helps you explain how your code scales and shows you know how Ruby handles repeated actions.

Self-Check

"What if we replaced each with map? How would the time complexity change?"