4 min read
Printing Output: puts, print, and p
Prerequisites: Ruby syntax basics
Ruby has three everyday ways to print:
| Method | Adds a new line? | Shows |
|---|---|---|
puts |
Yes | A friendly version for people |
print |
No | A friendly version, with no new line |
p |
Yes | A developer view that shows the type |
Example
puts "Hello"
print "Same "
print "line"
puts
p "Hello"
p 42
puts nil
p nil
puts [1, 2]
p [1, 2]
Expected output
Hello
Same line
"Hello"
42
nil
1
2
[1, 2]
Line by line:
printtwice keeps both words on one line; the bareputsthen ends that line.p "Hello"shows the quotes, so you can tell it's a string. That's whypis the go-to tool for debugging — it shows exactly what a value is.puts nilprints an empty line, whilep nilprintsnil.putsprints each element of an array on its own line;pshows the array itself.
Common mistakes
- Debugging with
putsand being confused when""(an empty string) andnilboth print as a blank line. Usepto see the difference.
Practice
Print Loading... and then done on the same line, followed by a
new line.
Show solution
print "Loading..."
puts "done"