# How to define a multiline string in Ruby

*Note: The following was tested with Ruby 2.6.6*

> Keyword: Heredoc

### What is heredoc?

[Heredoc](https://en.wikipedia.org/wiki/Here_document) 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?

```ruby
string = <<~HEREDOC
  How are you?
HEREDOC
```

* Start with `<<-` or `<<~`.
    
* The word `HEREDOC` can be replaced wit[h any t](https://en.wikipedia.org/wiki/Here_document)ext, ex. `SQL`, `HTML`[etc.](https://en.wikipedia.org/wiki/Here_document)
    
* End with the word you have defined, ex. `HEREDOC`.
    

### How to use string interpolation with a heredoc?

It's simple.

```ruby
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 th[e singl](https://en.wikipedia.org/wiki/Here_document)e quotes around the heredoc name.

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

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

`<<-`

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

`<<~`

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

`<<-` will maintain the original indentation. Ruby 2.3 introduce[d the s](https://en.wikipedia.org/wiki/Here_document)quiggly heredoc `<<~` which can removes extra indentation.

### How to remove an extra newline?

You might notice that there [is a new](https://en.wikipedia.org/wiki/Here_document)line character `\n` at the e[nd of t](https://en.wikipedia.org/wiki/Here_document)he return value. If you would like to remove an extra newline, `strip` will be useful.

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

---

### Reference

* [https://en.wikipedia.org/wiki/Here\_document](https://en.wikipedia.org/wiki/Here_document)
    
* [https://www.rubyguides.com/2018/11/ruby-heredoc](https://www.rubyguides.com/2018/11/ruby-heredoc/)
    
* [https://blog.saeloun.com/2020/04/08/heredoc-in-ruby-and-rails](https://blog.saeloun.com/2020/04/08/heredoc-in-ruby-and-rails)
