Printing Things
Learn another way to print something in Ruby.
We'll cover the following
Many exercises demonstrating Ruby basics include running a short program that outputs something to the terminal.
So far, we’ve mostly used the puts
method to do that.
What can be used instead of puts
?
However, there’s another method that’s even more useful when we’re trying to determine what a program is doing, why it’s doing it, and what might cause certain errors.
This is the p
method. To understand p
better, we’ll look at another method first, which is inspect
.
The inspect
method is available on any object in Ruby. It returns a string that’s a representation of the object itself—a representation that’s as close as possible to the code that we use to create the object.
puts 5.inspectputs "A string".inspectputs [1, 2, 3].inspect
Notice that the string returned from inspect
is conveniently exactly the same as the Ruby code that we used to create the object.
However, typing puts something.inspect
is cumbersome. That’s 12 characters to type next to the object itself!
Therefore, Ruby has a method to make our lives easier and do this work for us. That’s the p
method.
This method is implemented like so:
def p(object)puts object.inspectend
Whenever we’re trying to determine what a certain line of code does, what’s assigned to a variable, or what a method call returns, it’s best to use p
because it tells us exactly what the thing that we’re looking at is.
The puts
method, on the other hand, tries to be more clever than is necessary.
For example, when we pass an array to puts
, it outputs each of the objects on a separate line:
something = [1, 2, 3]puts somethingp something
Also, the output for numbers and strings that contain numbers is exactly the same when we use puts
:
puts 123puts "123"p "123"
From the output of puts
, it’s often unclear whether the object that we are looking at is an array that contains numbers, an array that contains strings, or just a long string that contains line breaks.
In short, puts
is useful when we’re writing a program that’s supposed to output something to the screen. This could be a command-line tool that we write to make our work easier that’s helpful at automating some repetitive work. On the other hand, p
is useful when we’re trying to understand what our code does, such as when we’re trying to understand a certain error.