puts, print and p
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:
# 12Give 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 Teap 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.0Compare 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.
The shortcut
Ask "Who is reading this?" A customer or user reads it: puts. You are building one line in pieces: print. You, the programmer, need to see exactly what a value is: p.
The symptom
puts item_nameprints a blank line. Isitem_namean empty string, ornil?
The trap is trusting puts while debugging. puts nil, puts "" and puts [] all print a blank line, so three very different values look the same.
Drills
Answer fast — trust the rule.
What does p "mocha" print?
Which method writes text without adding a newline at the end?
What does puts [1, 2, 3] print?
After total = puts 9.0, what is total?
A value prints as a blank line with puts. Which tool best shows whether it is nil or an empty string?
Remember
- puts is for people, print adds no newline, p is for programmers.
- Ask "who is reading this?" to pick one.
- Trap:
putshides the difference betweennil,""and[]; debug withp.
