0
0
Rubyprogramming~5 mins

Puts, print, and p output differences in Ruby - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Puts, print, and p output differences
O(n)
Understanding Time Complexity

We want to understand how the time it takes to show output changes when using different Ruby commands: puts, print, and p.

How does the way these commands work affect how long the program runs as output grows?

Scenario Under Consideration

Analyze the time complexity of the following Ruby code snippet.

array = [1, 2, 3, 4, 5]

array.each do |item|
  puts item
  print item
  p item
end

This code prints each item in the array three times using puts, print, and p.

Identify Repeating Operations

Look at what repeats in the code.

  • Primary operation: Looping through each item in the array and printing it three times.
  • How many times: Once for each item in the array (n times).
How Execution Grows With Input

As the array gets bigger, the number of print actions grows too.

Input Size (n)Approx. Operations
1030 (10 items x 3 prints each)
100300 (100 items x 3 prints each)
10003000 (1000 items x 3 prints each)

Pattern observation: The total print actions grow directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to print grows in a straight line as the number of items grows.

Common Mistake

[X] Wrong: "Using p is slower because it does more work, so it changes the time complexity."

[OK] Correct: While p shows extra details, it still prints once per item, so the overall time still grows linearly with input size.

Interview Connect

Understanding how output commands scale helps you explain program speed clearly and shows you can think about how code behaves as data grows.

Self-Check

What if we printed each item twice instead of three times? How would the time complexity change?