/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
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| puts | p | ||
|---|---|---|---|
| Converts with | to_s | to_s | inspect |
| Newline | After each argument (unless it already ends with one) | None | After each argument |
| Arrays | Flattened, one element per line | Printed with to_s on one line | Printed as a literal: [1, [2]] |
| nil | Empty line | Empty string | nil |
| "text" | text | text | "text" (with quotes) |
| Returns | nil | nil | The 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"vs1,nilvs empty string), and you can insert it inside an expression because it returns its argument.
Sources
Related pages
compare · rubyRuby symbol vs string: :name vs "name"A Ruby symbol is an immutable, unique identifier and a string is mutable text. Why h[:id] and h["id"] differ, JSON keys, conversion and when to use each one.errors · rubyRuby NoMethodError: undefined method for nilRuby raises NoMethodError undefined method for nil when a method is called on a value that is nil, often a failed lookup. Find the nil source; use &. or fetch.errors · rubyRuby: cannot load such file -- name (LoadError)Ruby raises LoadError when require finds no file: the gem is not installed for this Ruby or not in the Gemfile, or a local file needs require_relative instead.