Basics

Ruby puts

Printing with puts

Ruby puts outputs to console with string interpolation.

What is puts in Ruby?

puts is a method in Ruby used to output text to the console. It is short for 'put string' and is commonly used for displaying results or debugging. This method automatically adds a new line after the output, making it different from the print method, which does not add a new line.

Basic Usage of puts

The puts method can be used to display various types of data including strings, numbers, and more. Here is a simple example:

String Interpolation with puts

String interpolation allows you to embed expressions within a string. This is particularly useful when you want to include variable values within your strings. In Ruby, string interpolation is achieved using the #{} syntax within double-quoted strings. Here is an example:

Using puts with Arrays and Hashes

The puts method can also be used to output arrays and hashes. When applied to an array, puts will output each element on a new line. For hashes, Ruby will display the key-value pairs, each on a new line. Let's look at some examples:

Difference Between puts and print

While both puts and print are used to output text to the console, they differ in one key aspect: puts adds a new line after each argument, whereas print does not. Here's an example to illustrate this difference:

Conclusion

In this article, we explored the puts method in Ruby, which is essential for console output and debugging. By understanding how to use puts with different data types and incorporating string interpolation, you can effectively display information in your Ruby programs. Remember the distinction between puts and print for better control over your output format.

Previous
Gems