Using Heredoc Operator
There are several ways to create a multi-line string in Ruby. One way is to use the “<<” operator, also known as the “heredoc” or “here document” operator, followed by a delimiter of your choice. For example:
This is a
multi-line string
EOF
In this example, the delimiter is “EOF,” but it can be any string of your choice. The string assigned to the variable “string” includes all of the text between the “<<-EOF” and “EOF” delimiters, including any newline characters.
Using Triple Quotes
Another way to create a multi-line string is by using triple quotes (“””).
This is a
multi-line string
"""
This method will also preserve the newlines and indentation of characters.
Using Percent String Formatting
Alternatively, you can use %Q or %q followed by a delimiter of your choice.
multi-line string}
It is similar to double-quoted string.
Using the + Operator
You can also use the “+” operator to combine multiple strings to create a multi-line string in Ruby. An example demonstration is as shown:
line2 = "This is the second line"
line3 = "This is the third line"
string = line1 + "\n" + line2 + "\n" + line3
In this example, the + operator concatenates three strings, each representing a line of text, along with newline characters (\n). This creates a multi-line string, where a newline character separates each line.
We can also use the string interpolation technique to perform a similar action as:
Conclusion
This short tutorial covers the various methods and techniques you can use to create multi-line strings in Ruby.