Posted almost 8 years ago. Visible to the public.

Using heredoc for prettier Ruby code

You can use heredoc to avoid endlessly long lines of code that nobody can read. It looks like this:

def long_message puts(<<-EOT) Here goes a very long message... Sincerely, Dr. Foobear EOT end

<<-EOT will be somewhat of a placeholder: anything you write in the line after you used it will be its value until you write EOT in a single line.

You can use any string to flag your heredocs. T0 be more verbose you can use something else – your IDE may even be aware of it, for example RubyMine understands <<-SQL, <<-HTML, <<-XML, <<-JSON, etc and highlights correctly.

Multiple heredocs in one line

Now what if you want to do this more than once per line? Easy:

def long_messages html_escape(<<-ONE) + '<hr />' + html_escape(<<-TWO) Here goes my first very long message. Yeehaw! ONE This is the second message which is still long. It is long indeed. TWO end

<<- vs <<

You can also omit the dash and just write <<EOT – if you do this, your terminating sequence must be at the very beginning of the line. It's less pretty:

def foo stuff do something(<<-EOT) + something_else Here goes my content. EOT # vs: something(<<EOT) + something_else Here goes my content. EOT end end

Notes & Caveats

  • Important: I somewhat cheated here. Any spaces from the beginning of a line will be part of the string:

    puts <<-EOT Hello Universe EOT # Writes " Hello Universe\n"

    In many cases this is not a problem, e.g. when you want to pretty up many lines of monstrous SQL you would not care. Whenever you require one very specific string, like in specs, and if indentation causes you trouble, do not indent or just use a small method to strip leading spaces like #strip, #lstrip, #squish, etc.

  • Using heredoc you will have a linebreak after the last line. This can cause trouble (again, like when used in specs) – you can hack around it by saying <<-EOT.sub(/\n$/, '').
  • You can use regular string interpolation inside heredoc:

    puts <<EOT Dear #{}, ... EOT

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Arne Hartherz
Last edit:
8 months ago
by Jakob Scholz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more