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 SELECT * FROM food WHERE healthy = true SQL
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 HTML
Ruby Heredoc Interpolation
If you're wondering if you can use string interpolation with a heredoc...
The answer is yes!
Example:
type = "healthy" table = "food" query = <<-SQL SELECT * FROM #{table} WHERE #{type} = true SQL
You can disable the interpolation by surrounding the heredoc name with single quotes.
Like this:
doc = <<-'TIME' Current time is #{Time.now} TIME
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.
Example:
page = <<-HTML Heredocs are cool & useful HTML # " Heredocs are cool & useful\n" page = <<~HTML Heredocs are cool & useful HTML # "Heredocs are cool & useful\n" page = <<~HTML.strip Heredocs are cool & useful HTML # "Heredocs are cool & useful"
Now you can keep the extra spaces for readability.
While leaving them off in the actual string!
Summary
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!
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.
Thanks for reading Rod, I’m glad you found this helpful 🙂