Skip to content

/compare/ruby/puts-vs-print-vs-p

Ruby puts vs print vs p: what each one outputs and returns

The commands on this page have not been executed by our verification runner yet.updated
tool
Ruby
compares
puts / print vs p

puts writes each argument with to_s and adds a newline after each one (arrays are printed one element per line); it returns nil. print writes the arguments with to_s and adds no newline; it also returns nil. p writes each argument with inspect, so strings keep their quotes and nil is visible, adds a newline, and returns its argument, which makes it the tool for debugging. pp is like p with pretty-printing for nested data.

Side by side

ruby
puts "a", nil, [1, [2]]   # a / (empty line) / 1 / 2       returns nil
print "a", "b", "\n"      # ab                              returns nil
p "a", nil, [1, [2]]      # "a" / nil / [1, [2]]           returns ["a", nil, [1, [2]]]
x = p(42)                 # prints 42, x is 42
putsprintp
Converts withto_sto_sinspect
NewlineAfter each argument (unless it already ends with one)NoneAfter each argument
ArraysFlattened, one element per linePrinted with to_s on one linePrinted as a literal: [1, [2]]
nilEmpty lineEmpty stringnil
"text"texttext"text" (with quotes)
ReturnsnilnilThe argument (or an array of them)

When to use which

  • puts: normal program output, one line per value.
  • print: building a line in pieces, progress indicators, prompts before gets.
  • p / pp: debugging; you see the exact value and type ("1" vs 1, nil vs empty string), and you can insert it inside an expression because it returns its argument.

Sources