Home > Articles > Programming > Ruby

📄 Contents

  • Print
  • + Share This
  • 💬 Discuss

2.3 Using Here-Documents

If you want to represent a long string spanning multiple lines, you can certainly use a regular quoted string:

str = "Once upon a midnight dreary,
       While I pondered, weak and weary..."

However, the indentation will be part of the string.

Another way is the here-document, a string that is inherently multiline. (This concept and term are borrowed from older languages and contexts.) The syntax is the << symbol, followed by an end marker, then zero or more lines of text, and finally the same end marker on a line by itself:

str = <<EOF
Once upon a midnight dreary,
While I pondered weak and weary,...

Be careful about things such as trailing spaces on the final end marker line. Current versions of Ruby will fail to recognize the end marker in those situations.

Note that here-documents may be "stacked"; for example, here is a method call with three such strings passed to it:

some_method(<<str1, <<str2, <<str3)
first piece
of text...
second piece...
third piece
of text.

By default, a here-document is like a double-quoted string—that is, its contents are subject to interpretation of escape sequences and interpolation of embedded expressions. But if the end marker is single-quoted, the here-document behaves like a single-quoted string:

str = <<'EOF'
This isn't a tab: \t
and this isn't a newline: \n

If a here-document's end marker is preceded by a hyphen, the end marker may be indented. Only the spaces before the end marker are deleted from the string, not those on previous lines.

str = <<-EOF
  Each of these lines
  starts with a pair
  of blank spaces.

Here is a style I personally like. Let's assume the existence of the margin method defined here:

class String
  def margin
    arr = self.split("\n")             # Split into lines
    arr.map! {|x| x.sub!(/\s*\|/,"")}  # Remove leading characters
    str = arr.join("\n")               # Rejoin into a single line
    self.replace(str)                  # Replace contents of string

I've commented this fairly heavily for clarity. Parts of it involve features explained elsewhere in this chapter or later chapters.

It's used in this way:

str = <<end.margin
  |This here-document has a "left margin"
  |at the vertical bar on each line.
  |  We can do inset quotations,
  |  hanging indentions, and so on.

The word end is used naturally enough as an end marker. (This, of course, is a matter of taste. It "looks" like the reserved word end but is really just an arbitrary marker.) Each line starts with a vertical bar, which is then stripped off each line (along with the leading whitespace).

  • + Share This
  • 🔖 Save To Your Account


comments powered by Disqus