puts / print / p / pp
Methods for printing output to the console. Choosing the right method for your purpose makes debugging and display more efficient.
Syntax
# Converts the value to a string and outputs it with a trailing newline. puts value puts value1, value2 # Multiple arguments are printed one per line. # Outputs the value without a trailing newline. print value # Outputs a debug representation of the object (result of inspect). p value p value1, value2 # Outputs a more readable debug representation (Ruby 2.5+). pp value
Method List
| Method | Description |
|---|---|
| puts | Converts the value to a string, prints it, and appends a newline. When passed an array, each element is printed on its own line. |
| Converts the value to a string and prints it without appending a newline. | |
| p | Prints the result of the inspect method. Strings are displayed with quotation marks, and the return value is the object itself. |
| pp | Prints nested objects in a human-readable, formatted layout. Well-suited for debugging. |
| printf | Prints output using a format string. Equivalent to printf in C. |
Sample Code
# puts converts with to_s and prints with a newline.
puts "Hello" # Hello
puts 42 # 42
puts [1, 2, 3] # One per line: 1, 2, 3
# print outputs without a newline.
print "A"
print "B"
print "C"
puts # Add a newline → ABC
# p prints the inspect result (useful for debugging).
p "Hello" # "Hello" (with quotes)
p nil # nil
p [1, "two", :three] # [1, "two", :three]
# Compare puts and p.
puts "hello" # hello (no quotes)
p "hello" # "hello" (with quotes)
# pp displays nested data in a readable format.
data = {
name: "Tanaka",
scores: [85, 92, 78],
address: { city: "Tokyo", zip: "100-0001" }
}
pp data
# printf prints output with a format string.
printf("Name: %-10s Score: %3d\n", "Tanaka", 85)
printf("Name: %-10s Score: %3d\n", "Yamada Ichiro", 92)
Notes
Choose an output method based on your purpose. Use puts or print for user-facing output, and p or pp for debugging.
Because p returns the object itself, you can insert it in the middle of a method chain for quick debugging. Be careful not to leave p or pp calls in production code. These are debugging-only methods — use puts or a proper logger for production output.
If you find any errors or copyright issues, please contact us.