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.
| Feature | puts | p | |
|---|---|---|---|
| Adds newline after output | Yes | No | Yes |
| Outputs inspected object | No | No | Yes |
| Common use case | User-friendly output | Continuous output | Debugging |
| Handles arrays by printing each element on new line | Yes | No | Yes |
| Returns nil | Yes | Yes | Returns 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:
puts "Hello" puts [1, 2, 3]
print Equivalent
Here is how print prints output for the same data:
print "Hello" print [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.