How to define a multiline string in Ruby

Photo by rocknwool on Unsplash

How to define a multiline string in Ruby

·

2 min read

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, HTMLetc.

  • 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