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.

Press + to interact
puts 5.inspect
puts "A string".inspect
puts [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:

Press + to interact
def p(object)
puts object.inspect
end

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:

Press + to interact
something = [1, 2, 3]
puts something
p something

Also, the output for numbers and strings that contain numbers is exactly the same when we use puts:

Press + to interact
puts 123
puts "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.