How to Use p in Ruby: Simple Output with p Method
In Ruby,
p is a method that prints the value of an object to the console along with its inspected form, showing quotes for strings and other details. It is useful for debugging because it reveals the exact content of variables, unlike puts which prints a cleaner, user-friendly output.Syntax
The basic syntax of p is simple: you call p followed by the object you want to print inside parentheses or without them.
p object- prints the inspected form ofobject.p "Hello"- prints the string with quotes.
This method returns the object it prints, which can be useful in some cases.
ruby
p object
Example
This example shows how p prints different types of objects and returns the object itself.
ruby
p "Hello, world!" p [1, 2, 3] p 42
Output
"Hello, world!"
[1, 2, 3]
42
Common Pitfalls
A common mistake is confusing p with puts. p shows the inspected form, including quotes and array brackets, which is great for debugging but not always user-friendly. Also, p returns the object it prints, so using it in expressions can have side effects if you expect nil or other return values.
Wrong way:
puts "Hello, world!" p "Hello, world!"
Right way (use p when you want detailed output for debugging):
p "Hello, world!"
ruby
puts "Hello, world!" p "Hello, world!"
Output
Hello, world!
"Hello, world!"
Quick Reference
| Method | Description | Output Style | Returns |
|---|---|---|---|
| p | Prints inspected object | Shows quotes, brackets, and escapes | The object itself |
| puts | Prints user-friendly output | No quotes or brackets, just string form | nil |
| Prints without newline | Raw output, no newline | nil |
Key Takeaways
Use
p to print objects with detailed inspection for debugging.p shows quotes and array brackets, unlike puts.p returns the object it prints, which can affect expressions.For user-friendly output, prefer
puts instead of p.p is great for quickly checking variable contents during development.