Question
What is the difference between Ruby's print and puts methods? For example, why do they produce different output when used in this loop?
1.upto(1_000).each do |i|
print i if i.even?
end
Short Answer
By the end of this page, you will know when to use Ruby's print and puts, why their output looks different in loops, and how to format console output clearly.
Concept
print and puts are Ruby methods that write values to standard output, usually the terminal.
The main difference is whitespace after the value:
printwrites a value without automatically adding a newline.putswrites a value and adds a newline afterward.
A newline moves the cursor to the next line. Therefore, repeated calls to print usually appear on one line, while repeated calls to puts appear on separate lines.
This matters whenever a program displays lists, progress messages, reports, prompts, logs, or formatted text. Choosing the correct method makes terminal output easier for people and other tools to read.
Both methods return nil, so they are primarily used for their side effect: displaying output.
Mental Model
Think of the terminal as a sheet of paper.
printwrites on the current line and leaves the pen there.putswrites on the current line, then presses Enter before leaving the pen.
If you write several numbers with print, they run together unless you include your own separator. If you write them with puts, each number starts on a fresh line.
Syntax and Examples
Basic syntax:
print object
puts object
print does not add a newline
print "Hello"
print " world"
Output:
Hello world
puts adds a newline
puts "Hello"
puts "world"
Output:
Hello
world
Add separators yourself with print
print "red", ", ", "blue", ", ", "green", "\n"
Output:
red, blue, green
"\n" is a newline character. With print, you control every space and line break yourself.
Arrays behave differently
colors = ["red", "blue", "green"]
print colors
puts colors
Output:
["red", "blue", "green"]
red
blue
green
print displays the array as one inspected value. puts outputs each array element on its own line.
Step by Step Execution
Consider this loop:
1.upto(6).each do |i|
print i if i.even?
end
1.upto(6)produces the integers from1through6.eachruns the block once for every integer.i.even?isfalsefor1, so nothing is printed.i.even?istruefor2, soprint 2runs.- The same happens for
4and6. - Because
printadds no newline or spaces, the output is:
246
Now replace print with puts:
1.upto(6).each do |i|
puts i if i.even?
end
Each successful call adds a newline, so the output is:
2
4
6
The condition and loop are unchanged. Only the output formatting method changed.
Real World Use Cases
- Command-line lists: Use
putsto show one filename, user, or error per line. - Progress indicators: Use
printto keep a status message on one line, such asLoading.... - Formatted reports: Use
printwith explicit spaces, tabs, or delimiters for compact table-like output. - Simple scripts: Use
putsfor readable messages such asputs "Backup complete". - CSV-like output: Use
printwhen you need precise separators:
print name, ",", email, "\n"
- Debugging:
puts valueis a quick way to inspect simple values during development, althoughp valueis often more informative for strings and objects.
Real Codebase Usage
In real Ruby projects, puts is most often used for simple command-line scripts, learning exercises, one-off diagnostics, and user-facing terminal messages.
For structured output, developers usually make formatting explicit:
users.each do |user|
puts "#{user.id}: #{user.name}"
end
For a single-line prompt, use print so the user types on the same line:
print "Enter your name: "
name = gets.chomp
puts "Hello, #{name}!"
For reusable application code, developers commonly prefer a logger over puts:
logger.info("Import completed")
logger.warn("Missing email address")
Loggers can include timestamps, severity levels, and configurable destinations. puts remains useful for small scripts and direct terminal interaction.
Common Mistakes
Expecting print to separate values
# Runs, but the output is hard to read.
[2, 4, 6].each { |number| print number }
# Output: 246
Add a separator or use puts:
[2, 4, 6].each { |number| print "#{number} " }
# Output: 2 4 6
Forgetting a newline after a prompt
print "Done"
Your shell prompt may appear directly after Done. Add a newline when the message is complete:
puts "Done"
Assuming puts prints an array like print
puts ["a", "b"]
Output:
a
b
puts prints array elements separately. Use p or print array.inspect if you need the bracketed representation:
p ["a", "b"]
# ["a", "b"]
Using output methods as if they return the displayed value
result = puts "Hello"
# result is nil
Store the value first if you need it later:
message = "Hello"
puts message
# message is still "Hello"
Confusing puts with putc
putc outputs one character, based on a character or character code. It is not a replacement for puts when printing normal lines of text.
Comparisons
| Method | Adds newline? | Typical use | Array behavior |
|---|---|---|---|
print | No | Keep output on one line; control formatting manually | Prints the array representation |
puts | Yes | Display readable lines | Prints each element on a separate line |
p | Yes | Debugging Ruby values | Uses inspect, showing quotes and escape sequences |
warn | Yes | Warnings and diagnostic messages | Writes to standard error instead of standard output |
For strings, compare puts and p:
text = "hello\nworld"
puts text
p text
Output:
hello
world
"hello\nworld"
Use puts to show text as a person should read it. Use p to inspect Ruby's representation of a value while debugging.
Cheat Sheet
print "Hello" # Hello (no newline)
puts "Hello" # Hello + newline
print "Hello\n" # Hello + manual newline
p "Hello\n" # "Hello\\n" + newline; useful for debugging
- Use
putsfor one message per line. - Use
printfor prompts or tightly controlled formatting. - Add spaces and
"\n"manually when usingprint. puts [1, 2]prints1and2on separate lines.print [1, 2]prints[1, 2].- Both
printandputsreturnnil. - Use
pwhen you need to see quotes, escapes, or an object'sinspectrepresentation.
FAQ
Does puts always add a newline in Ruby?
Yes. puts writes a line ending after each argument it outputs. It also avoids adding an extra newline if a string already ends in one.
Why do numbers run together when I use print in a loop?
print does not add spaces or line breaks. Add a separator yourself, such as print "#{number} ", or use puts.
Should I use print or puts for a user prompt?
Use print so the user's input appears on the same line as the prompt:
print "Age: "
age = gets.chomp
What is the difference between puts and p?
puts displays values in a human-readable form. p displays inspect output, which is better for debugging strings, arrays, hashes, and objects.
Why does puts print every array item on a new line?
puts treats arrays specially and recursively outputs their elements. Use p array or print array.inspect to see the whole array representation on one line.
Do print and puts return the text they display?
No. Both return nil. Their purpose is output, not value transformation.
Is puts suitable for application logging?
It is fine for small scripts, but production applications usually use a logging tool so messages can have levels, timestamps, and configurable destinations.
Mini Project
Description
Create a small command-line even-number reporter. It demonstrates how print and puts change the layout of the same data, and it uses a prompt that keeps user input on the same line.
Goal
Ask for a maximum number, then display the even numbers both inline and one per line.
Requirements
Use print to ask the user for a maximum number.
Read the input and convert it to an integer.
Display all even numbers from 1 through the maximum on one line.
Display the same even numbers again, with one number per line.
Handle a maximum number smaller than 2 without crashing.
Keep learning
Related questions
Add a Default Value to an Existing Column in a Rails Migration
Learn how to add or change a default value on an existing database column using Rails Active Record migrations safely.
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.