0
0
Rubyprogramming~5 mins

Block parameters in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Block parameters
O(n)
Understanding Time 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.

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 using a block with a parameter.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The each method 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.
How Execution Grows With Input

As the list gets bigger, the number of times the block runs grows the same way.

Input Size (n)Approx. Operations
1010 times the block runs
100100 times the block runs
10001000 times the block runs

Pattern observation: The work grows directly with the number of items; double the items means double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items you process.

Common Mistake

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

Interview Connect

Understanding how blocks with parameters work helps you explain how Ruby handles repeated tasks clearly and efficiently.

Self-Check

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