There are many ways to print something in Ruby.
Here are the most useful:
But how are these different?
And when should you use one or the other?
That’s what you’re going to learn in this article!
How to Print Without A Newline
When you want to print something on the screen for the user to see, you normally use
puts "Hello there!"
Puts automatically adds a new line at the end of your message every time you use it.
If you don’t want a newline, then use
The next time you
print 123 print 456 print 789 123456789
But if you use puts:
puts 123 puts 456 puts 789 123 456 789
Every message has its own line!
Puts also treats arrays in a different way.
puts [1,2] 1 2 print [1,2] [1,2]
Here’s another difference:
Puts attempts to convert everything into a string (by calling
Why is that important?
Because if you’re trying to
puts an array with nil values…
It’s going to show some blanks lines!
puts [1,nil,nil,2] 1 2
- Convert things to strings, even if that means an empty string
- Adds a new line to the end of your messages
- Displays array elements one-per-line
Debug Output With P
What about puts vs p?
p is a method that shows a more “raw” version of an object.
> puts "Ruby Is Cool" Ruby Is Cool > p "Ruby Is Cool" "Ruby Is Cool"
p useful for?
When you’re looking for things like (normally invisible) newline characters, or you want to make sure some value is correct, then you use
- puts always returns nil
- p returns the object you pass to it
This is a more technical difference…
But it can show up if you try to
puts a variable as the last line of a method, and you’re using the return value of that method.
def numbers puts 123 end numbers # nil
In this example, the
numbers method will display 123 on the screen, but its return value will be
If you try:
result = numbers
result will be
nil, instead of 123.
But if you use
p then it will work.
Ruby has yet another printing method.
This is like
p, but it prints big hashes & arrays in a nicer way.
Note that older version of Ruby (pre 2.4) need to do
require 'pp' to get access to this method.
You’ve learned about the differences between puts, print & p in Ruby!
Now it’s practice time.
If you practice with something new immediately you’ll integrate this information into your knowledge base, if you don’t practice you’ll forget & you’ll not make progress.