2

One of the ways to write a multi-line string in Ruby is the "here document", or "heredoc", with syntax like:

<<~HEREDOC
  My multi-line string
  literal goes here!
HEREDOC

My understanding is that any identifier (word) can be used in place of where HEREDOC was used in the above example. (It doesn't have to be the word HEREDOC.)

Is there a documented best practice -- for code readability, and conformity to standards -- for choosing the name to use in a heredoc declaration?

Observations I've made:

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

  • The word SQL seems common when defining a SQL statement -- regardless of the purpose of the statement.
  • Code examples (including in the official documentation, and in the canonical StackOverflow question on multi-line strings in Ruby linked above) often use HEREDOC, or EOS (presumably meaning "end-of-string" -- even though the identifier appears both at the beginning and end of the string literal).
  • Sometimes, a word describing the value being stored is used as the heredoc identifier -- as is typically done when declaring a standard variable.
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
  • 1
    Some of CRuby's tests and at least two standard libraries such as [`forwardable`](https://github.com/ruby/ruby/blob/v3_0_0/lib/forwardable.rb#L226-L236) use lowercase identifiers (`begin;` and `end;` - note the trailing semicolon) to mimic `begin` ~ `end`. – cremno Feb 16 '21 at 20:23
  • 1
    There is no official standard - your observations actually cover the best practices quite well. – eugen Feb 16 '21 at 20:25
  • Don't forget you can write expressions such as `arr = <<~BITTER_END.split(/\n+/) ... BITTER_END #=> ["My multi-line string", "literal goes here!"]` – Cary Swoveland Feb 16 '21 at 20:36
  • 1
    Worth to mention, not sure if this is related with some extension, but in VSCode (and probably other IDEs), the heredoc data will be highligthed when its name matches one of the allowed formats, like [HTML](https://i.stack.imgur.com/A7JxT.png) or [SQL](https://i.stack.imgur.com/uq5wo.png) (and most likely others, I just found those two in my code). So, that's an extra reason to use an appropiated heredoc name for the given content. – Alter Lagos Feb 16 '21 at 23:23
  • 1
    And forgot to mention it, but the [ruby style guide](https://github.com/rubocop-hq/ruby-style-guide#heredocs) doesn't say anything about what's best/worst related with heredoc naming, so I think your observations are good enough. – Alter Lagos Feb 16 '21 at 23:28
  • That linked style guide does mention `Use descriptive delimiters for heredocs. Delimiters add valuable information about the heredoc content, and as an added bonus some editors can highlight code within heredocs if the correct delimiter is used.` which would make a good (and non-opinion-based) answer. – Jon Schneider Feb 19 '21 at 14:38

0 Answers0