0
0
Rubyprogramming~5 mins

IRB for interactive exploration in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: IRB for interactive exploration
O(n)
Understanding Time Complexity

When using IRB, we run Ruby code line by line to explore ideas quickly.

We want to understand how the time it takes grows as we try different commands or run code snippets.

Scenario Under Consideration

Analyze the time complexity of running a loop inside IRB.

10.times do |i|
  puts i * 2
end

This code prints double the numbers from 0 to 9, showing a simple repeated action.

Identify Repeating Operations

Look at what repeats when this code runs.

  • Primary operation: The loop runs the print command multiple times.
  • How many times: Exactly 10 times, once for each number from 0 to 9.
How Execution Grows With Input

As the number of times the loop runs increases, the work grows in a simple way.

Input Size (n)Approx. Operations
1010 print actions
100100 print actions
10001000 print actions

Pattern observation: If you double the input, the work doubles too.

Final Time Complexity

Time Complexity: O(n)

This means the time grows directly in proportion to how many times the loop runs.

Common Mistake

[X] Wrong: "Running code in IRB is always slow because it is interactive."

[OK] Correct: IRB runs each command quickly; the time depends on the code you run, not the tool itself.

Interview Connect

Understanding how code runs step-by-step in IRB helps you think about how your programs grow and perform in real projects.

Self-Check

"What if we changed the loop to run nested loops inside IRB? How would the time complexity change?"