0
  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?

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
Sreeraj Chundayil
  • 5,548
  • 3
  • 29
  • 68
  • 1
    This feature is called here doc. It's a way to define multiline strings. The result contains all **lines** between `<<-TPL` and `TPL`. `gsub(/^\s+/,'')` is applied to this string. – sschmeck Nov 23 '16 at 15:06
  • @Jordan: What's the difference between `duplicate` and `that solved my problem` tags? – Sreeraj Chundayil Nov 23 '16 at 15:18

2 Answers2

2

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.

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
1

Unfortunately there are many uses for the << operator in Ruby. However, in your specific case the << is used for declaring a string that spans multiple lines. Which allows you to get the matrix looking standard output.

What does << mean in Ruby? is a link that has many others

Community
  • 1
  • 1
Billy Ferguson
  • 1,429
  • 11
  • 23