Heredoc Indentations
This was the tip of the week in the June 17, 2021 Ruby Weekly Newsletter.
There are a few different ways to start [heredocs] <<
, <<-
and <<~
. After that, every heredoc has an identifier/delimiter (typically in uppercase and relevant to the purpose of the heredoc, like SQL
), the multiline string, and then the same identifier at the end. I’ve seen the three starts (<<
, <<-
and <<~
) used interchangeably in some codebases, yet there is a critical difference between them: each treats indentation differently.
For <<
, the ending identifier cannot be indented, and any indentations in the text will be treated as whitespace:
ugly_indented_code = <<NO_DASH
This doesn't read well for indented code
because it means that the end idenfier
will be all the way to the left
NO_DASH
The next start, <<-
, allows us to indent the end identifier, but will also preserve all whitespace:
too_much_whitespace = <<-STRAIGHT_DASH
The straight dash will also track indented strings
with a whole lot of whitespace
STRAIGHT_DASH
=> " The straight dash will also track indented strings\n with a whole lot of whitespace\n"
Lastly, using the tilde or ‘squiggly dash’ <<~
allows us to indent the end identifier, and also de-indents the content of the whole string to align with the least indented part of the string:
less_whitespace = <<~SQUIGGLY_DASH
Squiggly dash allows for indented end identifier
And indents the content of the whole string
To align with the least indented part of the string
SQUIGGLY_DASH
=> "Squiggly dash allows for indented end identifier\n And indents the content of the whole string\n To align with the least indented part of the string\n"
This last option is the most popular because it allows the end identifier to be intented, and has the least whitespace preserved within the String itself.