InQusitive InQusitive - 17 days ago 8
Ruby Question

What does <<- mean in ruby?

template = <<-TPL.gsub(/^\s+/,'')
╭───────╮
| X X X |
| X X X |
| X YYX |
| X X X |
╰───────╯
TPL


This is a snippet from
gem rubycards
.

I understand that it is storing some string in template. But what does
<<-
do?

Answer

It is called heredoc:

If you are writing a large block of text you may use a “here document” or “heredoc”:

expected_result = <<HEREDOC

This would contain specially formatted text.

That might span many lines
HEREDOC

The heredoc starts on the line following << HEREDOC and ends with the next line that starts with HEREDOC. The result includes the ending newline.

You may use any identifier with a heredoc, but all-uppercase identifiers are typically used.

You may indent the ending identifier if you place a “-” after <<:

  expected_result = <<-INDENTED_HEREDOC
This would contain specially formatted text.

That might span many lines
  INDENTED_HEREDOC

Note that the while the closing identifier may be indented, the content is always treated as if it is flush left. If you indent the content those spaces will appear in the output.