Basics

Crystal puts

Printing with puts

Crystal puts outputs to console with string interpolation.

Introduction to Crystal puts

The puts method in Crystal is used to output text to the console. It automatically appends a newline character to the end of the output, making it ideal for printing messages or data with each call appearing on a new line. This method is highly versatile, allowing for the inclusion of string interpolation, which simplifies the inclusion of variable data within strings.

Basic Usage of puts

To use puts, simply call it with a string or any data type that supports string conversion. Here's a basic example:

The above code will print Hello, World! to the console, followed by a newline.

Using String Interpolation

String interpolation allows you to embed variables directly within a string. This is achieved by placing the variable name inside curly braces within a double-quoted string.

In this example, the variable name is interpolated into the string, resulting in the output: Hello, Alice!

Working with Different Data Types

The puts method can handle various data types, converting them to strings where necessary. For instance, you can output numbers, arrays, or hashes directly.

Each line will be printed on a new line in the console, demonstrating puts's ability to manage different types of data.

Combining puts with Expressions

Expressions can be evaluated within the interpolation, allowing for dynamic output:

This will print: The sum of 2 and 3 is 5. demonstrating how expressions are evaluated within a string.

Conclusion

The puts method in Crystal provides a straightforward way to output text and data to the console. Its support for string interpolation and automatic handling of various data types makes it an essential tool for Crystal programmers.

In the next post, we will explore Functions in Crystal, taking our knowledge of this powerful language to the next level.

Previous
Shards