Rails Insights

Using Heredoc for Multi-line Strings in Ruby

Introduction

When working with Ruby, there are often times when you need to work with multi-line strings. One way to handle this is by using Heredoc, a syntax that allows you to define a multi-line string within your code. In this article, we will explore how to use Heredoc for multi-line strings in Ruby.

What is Heredoc?

Heredoc is a way to define a multi-line string in Ruby. It allows you to create a block of text that spans multiple lines without having to use escape characters like \n for new lines. Heredoc is enclosed by << followed by a delimiter, which can be any string of your choice. The block of text ends when the delimiter is encountered on a line by itself.

Using Heredoc in Ruby

Let's take a look at how you can use Heredoc in Ruby. Here is a simple example:

<<-TEXT
This is a multi-line string
that spans multiple lines
using Heredoc in Ruby.
TEXT

In the above example, <<-TEXT is the Heredoc syntax, and TEXT is the delimiter. The block of text starts after <<-TEXT and ends when TEXT is encountered on a line by itself.

Indentation in Heredoc

One thing to note when using Heredoc is that the indentation of the delimiter will be preserved in the block of text. This means that if you indent the delimiter, the block of text will also be indented. Here is an example:

<<-TEXT
    This is a multi-line string
    that preserves indentation
    using Heredoc in Ruby.
TEXT

In the above example, the block of text will be indented because the delimiter is indented. If you want to remove the indentation, you can use the <<-TEXT syntax without any indentation.

Interpolation in Heredoc

You can also use string interpolation within a Heredoc block. This allows you to insert variables or expressions into the multi-line string. Here is an example:

name = "Alice"
<<-TEXT
Hello, #{name}!
This is a multi-line string
using Heredoc in Ruby.
TEXT

In the above example, the variable name is interpolated within the Heredoc block, allowing you to dynamically insert values into the multi-line string.

Conclusion

Using Heredoc for multi-line strings in Ruby is a convenient way to work with blocks of text that span multiple lines. It allows you to define a block of text without having to worry about escape characters for new lines. By using Heredoc, you can easily create and manipulate multi-line strings in your Ruby code.

Published: May 31, 2024

© 2024 RailsInsights. All rights reserved.