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 & formatting.

This is used to embed snippets of code, like SQL or HTML.

Here’s an example:

query = <<-SQL
WHERE healthy = true

You use this syntax to define a heredoc in Ruby.

You start with the symbol <<-, then a word that represents the name for this heredoc, then the heredoc contents, then you close the heredoc with that some word on its own line.

Another way to do this is to use %Q:

query = %Q(

  Article about heredocs


You'll get an extra newline at the start & end of this string. A heredoc (or calling the strip method) solves that.

Here's a Ruby heredoc without trailing newline:

query = <<-HTML.chomp

  Article about heredocs


Ruby Heredoc Interpolation

If you're wondering if you can use string interpolation with a heredoc...

The answer is yes!


type  = "healthy"
table = "food"

query = <<-SQL
SELECT * FROM #{table}
WHERE #{type} = true

You can disable the interpolation by surrounding the heredoc name with single quotes.

Like this:

doc = <<-'TIME'
Current time is #{}

Ruby Squiggly Heredoc

How can you remove extra indentation at the start of every line?

That's what the squiggly heredoc is for.

Introduced in Ruby 2.3, the squiggly heredoc removes extra indentation for you.


page = <<-HTML
  Heredocs are cool & useful

# "  Heredocs are cool & useful\n"

page = <<~HTML
  Heredocs are cool & useful

# "Heredocs are cool & useful\n"

page = <<~HTML.strip
  Heredocs are cool & useful

# "Heredocs are cool & useful"

Now you can keep the extra spaces for readability.

While leaving them off in the actual string!


You've learned how to use heredocs in Ruby for embedding multiline strings in your code. This can be useful for writing tests for your code or having small bits of data available without having to read a file.

Thanks for reading!

2 thoughts on “How To Use Heredoc in Ruby”

  1. Thanks for this, Jesus! I often find myself wanting to output long segments of HTML with interpolated data but can never remember the syntax! LOL! This is really helpful.

Comments are closed.