The Difference between Puts and Print in Ruby

09/23/2021

Contents

In this article, you will learn about the difference between puts and print in Ruby.

The difference between puts and print in Ruby

In Ruby, both puts and print are used to output information to the console or terminal. However, there are some differences between the two that are worth noting.

puts is short for “put string” and is used to display a string of characters to the console followed by a newline character. For example:

puts "Hello, world!"

This would output:

Hello, world!

Notice how there is a newline character at the end of the output. puts automatically adds a newline character to the end of the output, which can be useful for separating different lines of output.

print, on the other hand, is used to display a string of characters to the console without adding a newline character at the end. For example:

print "Hello, "
print "world!"

This would output:

Hello, world!

Notice how there is no newline character at the end of the output. print outputs the string exactly as it is given to it, without any extra formatting.

Another difference between puts and print is how they handle arrays. If you pass an array to puts, each element of the array will be displayed on a separate line with a newline character at the end of each line. For example:

arr = [1, 2, 3]
puts arr

This would output:

1
2
3

If you pass an array to print, the entire array will be displayed on a single line without any extra formatting. For example:

arr = [1, 2, 3]
print arr

This would output:

[1, 2, 3]