Ruby

Difference Between Puts and Print in Ruby

Printing variables or strings to the console is a basic program functionality. However, in Ruby, we have two main methods to print values to the console. These methods include:

  1. The print function
  2. The puts function

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:

puts "Hello, World!"

This will print the string “Hello, World!” followed by a new line to the console.

Hello, World!
=> nil

We can also pass any variables, expressions, or return of a function to the puts method as shown:

name = "Peter"
puts "My name is #{name}"

Output:

My name is Peter
=> 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 "Hello, "
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.

a = [1,2,3]
puts a

Resulting output:

1
2
3
=> nil

Using the print function:

a = [1,2,3
print a

Resulting output:

[1, 2, 3]=> nil

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list