Skip to content

Instantly share code, notes, and snippets.

@emilong
Last active August 15, 2019 21:40
Show Gist options
  • Save emilong/2496c44892400a658f520a93830f26b3 to your computer and use it in GitHub Desktop.
Save emilong/2496c44892400a658f520a93830f26b3 to your computer and use it in GitHub Desktop.
Heredocs in Ruby

Heredocs in Ruby!

Heredocs are a way to write multi-line strings in Ruby. Some of their syntax can be a bit tricky to figure out, especially when calling methods on them as literals or passing them as arguments to methods, but both can be done!

Original, verbatim Heredoc with whitespace preserved

<<-EOF
This
  reminds
    me
      of
        e.
   e.
 cummings
po  et ry
EOF

# => "This\n  reminds\n    me\n      of\n        e.\n   e.\n cummings\npo  et ry\n"

The Squiggly Heredoc gets rid of newlines and trims the front of each line when consistently indented

<<~EOF
  This 
  probably
  doesn't
  need
  to
  be
  multiple
  lines
  but
  it
  certainly
  makes
  a
  statement!
EOF
# => "This \nprobably\ndoesn't\nneed\nto\nbe\nmultiple\nlines\nbut\nit\ncertainly\nmakes\na\nstatement!\n"

Squiggly Heredoc won't remove the beginning whitespace with inconsistent indentation

<<~EOF
This 
  won't
    really
  take
advantage
  of
the
     squiggly
EOF

# => "This \n  won't\n    really\n  take\nadvantage\n  of\nthe\n     squiggly\n"

Use whatever delimiter you like, but certain editors (and GitHub apparently!) have syntax highlighting support for SQL and other languages

<<~SQL
  SELECT * FROM squigglies
    JOIN lines ON squigglies.line_id = lines.id
SQL

What if you need to call a method on a heredoc string? You have to do it on the opening delimiter:

<<~SQL.squish
  SELECT * FROM squigglies
    JOIN lines ON squigglies.line_id = lines.id
SQL

Similarly, if you need to pass a heredoc as an argument to a function and follow it with other arguments, the comma goes after the opening delimiter:

SomeRailsModel
  .where(
     <<~SQL.squish,
       some_column = ?
     SQL
     "my value"
   )
   
# equivalent to:
SomeRailsModel
  .where("some_column = ?, "my value")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment