Puts, print, and p output differences in Ruby - Time & Space 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?
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.
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).
As the array gets bigger, the number of print actions grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 30 (10 items x 3 prints each) |
| 100 | 300 (100 items x 3 prints each) |
| 1000 | 3000 (1000 items x 3 prints each) |
Pattern observation: The total print actions grow directly with the number of items.
Time Complexity: O(n)
This means the time to print grows in a straight line as the number of items grows.
[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.
Understanding how output commands scale helps you explain program speed clearly and shows you can think about how code behaves as data grows.
What if we printed each item twice instead of three times? How would the time complexity change?