Printing an Array on One Line in Ruby
Greetings, friends! It's very common to use the Kernel#puts method to print information to the screen.
puts "Greetings, friends!"
If we tried using this method on an array, then we'd see each element of the array printed on a new line.
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.
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.