Skip to the workspace
Pebellslearn by building
Ruby Basics  ›  Lesson

puts, print and p

puts, print, p 12 minputs prints readable text with a newline, print adds no newline, and p shows a value's inspected form and returns it, which makes it the tool for debugging.

ruby / puts, print and p

Explore each scene at your own pace.

01 · The rule

The rule

puts, print and p

puts prints readable text with a newline, print adds no newline, and p shows a value's inspected form and returns it, which makes it the tool for debugging.

Compare readable output with diagnostic representations and newline behavior.

At closing time, Bean Cart's script should print a little report. Ruby gives you three everyday ways to write to the screen, and they differ in two small details that matter: whether a newline is added, and whether you see the value as a reader would or as a programmer would.

The rule

puts is for people, print adds no newline, p is for programmers.

puts ("put string") converts each argument to text and ends each one with a newline:

puts "Bean Cart"
puts "Cups sold:", 12
# Bean Cart
# Cups sold:
# 12

Give puts an array and it prints each element on its own line. Give it nil and it prints an empty line. It always returns nil.

print writes the text and adds nothing, so the next output continues on the same line:

print "Latte "
print "Mocha "
print "Tea\n"
# Latte Mocha Tea

p shows the inspected form of a value, the way you would type it in code. Strings keep their quotes, nil shows as nil, and hidden characters become visible. It also returns its argument, which makes it handy for debugging in the middle of an expression:

p "latte"          # "latte"
p nil              # nil
p "tea\n"          # "tea\n"
total = p(4.5 * 2) # prints 9.0, and total is 9.0

Compare with puts "latte", which prints latte with no quotes, and puts nil, which prints only a blank line. When you are hunting a bug, p tells you the truth; puts makes things look nice.

For bigger structures there is also pp ("pretty print"), which spreads nested hashes and arrays over several lines.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.