Printing an Array on One Line in Ruby

Published: Saturday, May 21, 2022
Updated: Sunday, May 22, 2022

Greetings, friends! It's very common to use the Kernel#puts method to print information to the screen.

ruby
Copied! ⭐️
puts "Greetings, friends!"
tip
You can try out this code by copying and pasting it to run.rb.

If we tried using this method on an array, then we'd see each element of the array printed on a new line.

ruby
Copied! ⭐️
puts ["pizza", "donuts", "potato"]

=begin OUTPUT:
pizza
donuts
potato
=end

If we wanted to print the array out on a single line instead, then we can make use of the Kernel#p method.

ruby
Copied! ⭐️
p ["pizza", "donuts", "potato"]
# OUTPUT: ["pizza", "donuts", "potato"]

The Kernel#p method will internally call the inspect method on the object passed into it (the array in our example). If we look at the Array#inspect method, then we can see that it is an alias for the Array#to_s method, which prints the object as a string. For Array objects in Ruby, it will print the array in a nice, readable format, similar to how we define arrays. It will surround the string with square brackets and separate each value with a comma.

The Kernel#p method is a nice utility for debugging purposes and helps you output values in special objects such as Arrays in a nice format.

If you want to learn more about the difference between the puts and p methods, please look at the next article.

Resources