Skip to main content

How to Print Output in Ruby with puts

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

puts is how a Ruby script writes to the terminal: it prints a value and ends the line. Two relatives fill the gaps: print doesn't end the line, and p shows a value the way Ruby sees it, quotes and all.

Syntax​

Syntax
puts <value>
print <value>
p <value>
PartWhat it does
putsPrints the value and a new line; each item of an array goes on its own line.
printPrints the value without a new line.
pPrints the value's inspect form, such as "text" with quotes, and returns the value.

The Ruby documentation for Kernel describes puts as "Equivalent to $stdout.puts(*objects) for the given objects", and notes that p "is designed for debugging purposes".

The Example​

The example prints a sentence, a number and an array with puts, builds one line from print and puts, and prints a string with p.

Prerequisites​

  • Ruby. This guide uses Ruby 4.0.10.

Step 1: Write the Code​

Create a file named main.rb:

main.rb, which puts Hello from Ruby, 42 and an array of a and b, prints No new line, then puts then a new line., and p's the string with quotes.

main.rb
puts 'Hello from Ruby'
puts 42
puts ['a', 'b']
print 'No new line, '
puts 'then a new line.'
p 'with quotes'

Step 2: Run It​

Terminal
ruby main.rb
Output
Hello from Ruby
42
a
b
No new line, then a new line.
"with quotes"

A zsh terminal where ruby main.rb prints Hello from Ruby, 42, a, b, No new line, then a new line., and the string with quotes.

  • puts ['a', 'b'] printed each item on its own line.
  • print left the line open for the next puts.
  • p kept the quotes, which shows that the value is a string.

The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Using puts to debug a valueputs nil prints an empty line, and puts '' looks the sameUse p, which shows nil and ""
Using print for every lineEverything runs together on one lineUse puts, or add "\n"
Expecting puts to return what it printedIt returns nilUse p when you need the value back

Troubleshooting​

SymptomLikely causeFix
An empty line where a value should beThe value is nil or ''Print it with p to see which
Output runs togetherprint doesn't end the lineSwitch to puts

FAQ​

Where does puts write?​

To standard output. For error messages, warn 'message' writes to standard error instead.

Why does p return its argument?​

So you can wrap it around an expression while debugging without changing what the code does: x = p 'a' printed "a" and set x to "a".

Conclusion​

puts prints a value and a new line, print leaves the line open, and p shows the value's inspected form for debugging.

Additional Resources​