Heredoc can be used to write blocks of text that span multiple lines while maintaining new lines and indentations. This is useful for multiline text strings or code snippets like SQL querys for example.
To define a heredoc use <<
and a string identifier. In general anything can be used but it is good practice to use an uppercase word to describe the content.
result = <<HEREDOC
Multiline text with empty lines.
And indentation.
HEREDOC
This is equivalent to:
result = "Multiline text with empty lines.\n\n And indentation.\n"
Notice that the ending HEREDOC
identifier cannot be indented in the code. If you want to indent it you have to use <<-
:
result = <<-HEREDOC
Multiline text with empty lines. (indented identifier)
And indentation.
HEREDOC
While the identifier can be indented the result here will be the same as in the previous version with <<
.
If you want to actually indent the content as well as the identifier so that the code is more readable and cleaned up you can use squiggly heredoc using <<~
.
result = <<~HEREDOC
Multiline text with empty lines. (removes indentation)
And indentation.
HEREDOC
This will result in the exact same string as in the last example. The indentation of the least-indented line will be removed from each line of the content.
Heredoc also allows string interpolation as you would expect it in a normal string.
result = <<~HEREDOC
#{1 + 1}
HEREDOC
This will return "2\n"
as a heredoc always includes the final new line.
To disable string interpolation you can use single quotes around the identifier.
result = <<~'HEREDOC'
#{1 + 1}
HEREDOC
Here the result is "\#{1 + 1}\n"
.
If you want to call a method on a heredoc you can place it directly at the end of the first identifier.
result = <<~HEREDOC.chomp
#{1 + 1}
HEREDOC
In this example this would return "2"
, as chomp
is used to get rid of the last newline.
As we can see heredoc is a good alternative to quoted strings because it greatly increases readability and maintainability.
Happy Coding!
P.S.: It is even possible to have heredoc behave like Kernel by using backticks to run commands.
result = <<~`HEREDOC`
ls -al \
| grep drw-
HEREDOC