Question

Ruby print vs puts: Output and Newlines Explained

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:

  • print writes a value without automatically adding a newline.
  • puts writes 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.

  • print writes on the current line and leaves the pen there.
  • puts writes 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.

Take Quiz

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. 1.upto(6) produces the integers from 1 through 6.
  2. each runs the block once for every integer.
  3. i.even? is false for 1, so nothing is printed.
  4. i.even? is true for 2, so print 2 runs.
  5. The same happens for 4 and 6.
  6. Because print adds 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 puts to show one filename, user, or error per line.
  • Progress indicators: Use print to keep a status message on one line, such as Loading....
  • Formatted reports: Use print with explicit spaces, tabs, or delimiters for compact table-like output.
  • Simple scripts: Use puts for readable messages such as puts "Backup complete".
  • CSV-like output: Use print when you need precise separators:
print name, ",", email, "\n"
  • Debugging: puts value is a quick way to inspect simple values during development, although p value is often more informative for strings and objects.
Take Quiz

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

MethodAdds newline?Typical useArray behavior
printNoKeep output on one line; control formatting manuallyPrints the array representation
putsYesDisplay readable linesPrints each element on a separate line
pYesDebugging Ruby valuesUses inspect, showing quotes and escape sequences
warnYesWarnings and diagnostic messagesWrites 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.

Take Quiz

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 puts for one message per line.
  • Use print for prompts or tightly controlled formatting.
  • Add spaces and "\n" manually when using print.
  • puts [1, 2] prints 1 and 2 on separate lines.
  • print [1, 2] prints [1, 2].
  • Both print and puts return nil.
  • Use p when you need to see quotes, escapes, or an object's inspect representation.

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.

Take Quiz

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.

Take Quiz

Keep learning

Related questions

View more