0
0
RubyComparisonBeginner · 3 min read

Puts vs Print vs P in Ruby: Key Differences and Usage

puts prints output with a newline, print prints without a newline, and p prints the inspected (debug-friendly) version of an object with a newline. Use puts for readable output, print for continuous output, and p for debugging.
⚖️

Quick Comparison

Here is a quick table comparing puts, print, and p in Ruby based on key factors.

Featureputsprintp
Adds newline after outputYesNoYes
Outputs inspected objectNoNoYes
Common use caseUser-friendly outputContinuous outputDebugging
Handles arrays by printing each element on new lineYesNoYes
Returns nilYesYesReturns the object printed
⚖️

Key Differences

puts prints the given argument followed by a newline, making output easy to read line by line. When given an array, it prints each element on its own line. It returns nil after printing.

print outputs the argument exactly as is, without adding a newline. This is useful when you want to continue printing on the same line. Like puts, it returns nil.

p is mainly for debugging. It prints the inspect version of the object, showing quotes around strings and other details. It adds a newline after output and returns the object itself, which can be handy in debugging chains.

⚖️

Code Comparison

Here is how puts prints output:

ruby
puts "Hello"
puts [1, 2, 3]
Output
Hello 1 2 3
↔️

print Equivalent

Here is how print prints output for the same data:

ruby
print "Hello"
print [1, 2, 3]
Output
Hello[1, 2, 3]
🎯

When to Use Which

Choose puts when you want clean, readable output with each item on its own line, ideal for user messages. Use print when you want to output text continuously without line breaks, such as progress indicators. Use p when debugging to see the exact representation of objects including quotes and special characters.

Key Takeaways

puts adds a newline and is best for readable output.
print outputs without newline for continuous printing.
p shows detailed object info for debugging.
puts prints arrays line by line; print prints arrays as is.
p returns the object printed, unlike puts and print which return nil.