TIL: How to define a multiline string in Ruby

TIL: How to define a multiline string in Ruby
Photo by Andrew Neel / Unsplash

Note: The following was tested with Ruby 2.6.6

Keyword: Heredoc

What is heredoc?

Heredoc is used for a form of multiline strings and preserves the line breaks and whitespace (including indentation) in the text.

How to define a heredoc in Ruby?

string = <<~HEREDOC
  How are you?
HEREDOC
  • Start with <<- or <<~.
  • The word HEREDOC can be replaced with any text, ex. SQL, HTML etc.
  • End with the word you have defined, ex. HEREDOC.

How to use string interpolation with a heredoc?

It's simple.

string = <<~HEREDOC
  How are you, #{User.first.name}?
HEREDOC
#=> "How are you, Lynn\n"

If you would like to disable the interpolation, you can put the single quotes around the heredoc name.

string = <<~'HEREDOC'
  How are you, #{User.first.name}?
HEREDOC
#=> "How are you, \#{User.first.name}?\n"

What's the difference between <<- and <<~?

<<-

string = <<-HEREDOC
  Today is a nice day.
HEREDOC
#=> "  Today is a nice day.\n"

<<~

string = <<~HEREDOC
  Today is a nice day.
HEREDOC
#=> "Today is a nice day.\n"

<<- will maintain the original indentation. Ruby 2.3 introduced the squiggly heredoc <<~ which can removes extra indentation.

How to remove an extra newline?

You might notice that there is a newline character \n at the end of the return value. If you would like to remove an extra newline, strip will be useful.

string = <<~HEREDOC.strip
  Today is a nice day.
HEREDOC
#=> "Today is a nice day."

Reference

Here document - Wikipedia
How To Use Heredoc in Ruby
What is a heredoc? A heredoc is a way to define a multiline string, while maintaining the original indentation &amp; formatting. This is used to embed snippets of code, like SQL or HTML. Here’s an example: query =
Heredocs and how to use them in Ruby and Rails
Ruby on Rails and ReactJS consulting company. We also build mobile applications using React Native