profile globe link mail twitter github file-pdf

Mateo Clarke

What I Learned Yesterday - Heredoc

Every day at AcademicWorks, the Engineering Team has a Dev Sync where we share something we learned from the day before. Here is what I learned yesterday…

What I learned

A heredoc (or Here document) is a way to declare a file or a long string inline. One of the advantages to saving a string in a heredoc is that you preserve line breaks, indentation and other white spaces. It also ignores quotations, so if you had a string with quotes in it, they don’t have to be escaped.

This is confusing to read:

"<pre>\n  <code>puts \"foobar\"</code>\n<pre>"

But this is equivalent and it reads much better.

  <code>puts "foobar"</code>

EOS here stands for “end of string”. It’s a common convention to use “EOS” with heredocs, but it doesn’t really matter. Any string after <<- is how you are telling the heredoc what to look for and when to terminate itself. Once it encounters “EOS” the second time, the heredoc knows it’s reached the… end of the string.

In our code base, I encountered this use of a heredoc in our code. We are using a method like html_code as a helper method. It’s a much prettier way to inject a string of HTML while preserving the code indentation we are familiar.

def html_code
  html_code = <<-HTML
    <div class="textile-meta">
      <div class="example">
        <span>Example Formatting: <strong>*bold*</strong>, <em>_italics_</em></span>


More resources