0
0
Rubyprogramming~5 mins

Puts, print, and p output differences in Ruby

Choose your learning style9 modes available
Introduction

We use puts, print, and p to show messages on the screen, but they do it in slightly different ways.

When you want to show a message with a new line after it, use <code>puts</code>.
When you want to show a message without adding a new line, use <code>print</code>.
When you want to see the exact value of something, including quotes or special characters, use <code>p</code>.
Syntax
Ruby
puts value
print value
p value
puts adds a new line after the output.
print does not add a new line.
p shows the value in a way that helps debugging (like showing quotes around strings).
Examples
This prints two lines, each with a new line after.
Ruby
puts "Hello"
puts "World"
This prints both words on the same line without spaces or new lines.
Ruby
print "Hello"
print "World"
This prints the strings with quotes, showing exactly what the values are.
Ruby
p "Hello"
p "World"
Sample Program

This program shows how puts, print, and p behave differently when printing.

Ruby
puts "Hello"
print "World"
p "!"
OutputSuccess
Important Notes

puts automatically adds a new line, so each call appears on its own line.

print keeps printing on the same line unless you add a new line character \n yourself.

p is useful for debugging because it shows the exact form of the value, including quotes for strings.

Summary

puts prints with a new line.

print prints without a new line.

p prints the value in a way that helps you see its exact form.