How to Print to the Ruby Console
When you're learning a new programming language, it is important to see your program's output. This is why repl.it is a convenient tool for beginners as you can see the results on the terminal instantly.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

When you're learning a new programming language, it is important to see your program's output. This guide can be used in an online Repl environment (like our variable lesson) or in the unix terminal by typing irb which will open an interactive Ruby session.

Using puts

In this lesson, we are going to learn the different options available to print messages to the Ruby console. The first way is to use the puts command. For example:

puts "A string"

Will display the content A string.

Using p

Another way to print to the console is:

p "A string"

The difference between these two methods is that the former method will not return any value back to you, whereas the second one will return a value. The image below shows this difference.

large

If you see, the puts method returns a value of nil

large

While the second option returns the value.

Though this difference may not be much now, you will discover how important this is as we progress through the course.

Another difference between the two methods is the way they process the array data structure. The p method prints the array in it's code form, and returns these values back to the user.

large

On the other hand, the puts method iterates through the collection to display individual values, and as mentioned above this returns a nil value.

large

The first set of values were printed with the command

It's important to know that both of these methods work with all data types including arrays and collections. Understanding these similarities and differences is important to ensure that you use the right command at the right time.