In this tutorial, we will discuss each function’s main differences and when to use one over the other.
Ruby Puts Function
We mainly use the puts function to print an output console or terminal. It stands for “put string,” similar to the print function. But it adds a new line character at the end of the output, causing the subsequent result to appear on a new line.
For example:
This will print the string “Hello, World!” followed by a new line to the console.
=> nil
We can also pass any variables, expressions, or return of a function to the puts method as shown:
puts "My name is #{name}"
Output:
=> nil
Ruby Print Function
Like the puts function, we use the print function to print output to the console. However, unlike puts, the function does not add a newline character at the end of the output. Instead, any subsequent output will appear on the same line as the previous output.
For example:
print "World!"
The example above will output the strings “Hello, World!” on the same line, with a space between “Hello, ” and “World!
Summary
The main difference between the puts and print functions in Ruby is how they handle newlines at the end of the output.
The puts function automatically adds a new line character at the end of the output, allowing any subsequent output to appear on a new line.
On the other hand, the print function does not add a newline character at the end of the output. Hence, any subsequent output will appear on the same line as the previous output.
Another difference worth noting is that the puts function will convert any passed object to a string before printing, whereas print will print the passed argument as it is.
puts a
Resulting output:
2
3
=> nil
Using the print function:
print a
Resulting output:
Another difference between the two functions is that the puts function returns nil. But print returns the passed argument, which can be helpful if you need to return the output of a print statement as a value.
Conclusion
In this article, you came across Ruby’s two most popular methods of printing output to the console. You also discovered the differences between these functions and when one is most applicable.