puts / print / p / pp
| Since: | Ruby 1.8(2003) |
|---|
Methods for printing output to the console. Choosing the right method for your purpose makes debugging and display more efficient.
Syntax
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
sample_puts_print_p_pp.rb
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: "user_a",
org: "org_a",
techniques: ["skill_a", "skill_b", "skill_c"]
}
pp data
# printf prints output with a format string.
printf("Name: %-15s Org: %s\n", "user_a", "org_a")
printf("Name: %-15s Org: %s\n", "user_b", "org_a")
Running the code produces the following output:
ruby puts_print_p_pp.rb
Hello
42
1
2
3
ABC
"Hello"
nil
[1, "two", :three]
hello
"hello"
{name: "user_a",
org: "org_a",
techniques: ["skill_a", "skill_b", "skill_c"]}
Name: user_a Org: org_a
Name: user_b Org: org_a
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.