Ruby

Ruby Multi-Line String

In Ruby, a multi-line string is a string that spans multiple lines of code.

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:

string = <<-EOF
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 (“””).

string = """
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.

string = %Q{This is a
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:

line1 = "This is the first line"
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:

string = "#{line1}\n#{line2}\n#{line3}"

Conclusion

This short tutorial covers the various methods and techniques you can use to create multi-line strings in Ruby.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list