I found this neat trick recently that someone posted to a Ruby forum on how to align heredocs in your code. Lets assume you have a small Ruby class that prints quotations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Quote

  def initialize
    @quote = <<-QUOTESTR
If you could kick the person
in the pants responsible for
most of your trouble, you
wouldn't sit for a month.
        - Theodore Roosevelt
QUOTESTR
  end

  def cite
    puts @quote
  end
end

q = Quote.new
q.cite

Running the code above, gets you this output,

If you could kick the person
in the pants responsible for
most of your trouble, you
wouldn't sit for a month.
        - Theodore Roosevelt

which is what we wanted, however the the code is harder to read because the @quote assignment is align in column 1. I would like to do indent the quote passage six (6) spaces to the right as such.

1
2
3
4
5
6
7
8
9
def initialize
    @quote = <<-QUOTESTR
      If you could kick the person
      in the pants responsible for
      most of your trouble, you
      wouldn't sit for a month.
              - Theodore Roosevelt
      QUOTESTR
  end

Now, however, when I run the code I get six (6) leading spaces in the output.

      If you could kick the person
      in the pants responsible for
      most of your trouble, you
      wouldn't sit for a month.
              - Theodore Roosevelt

Now comes the trick. You can actually send a message .gsub(/^ {6}/,’’) to the heredoc before it gets assigned to the variable, @quote.

@quote = <<-QUOTESTR.gsub(/^ {6}/,'')

Now we can have our heredoc indented and also worked as though it was flush to the left. Below is the final code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Quote

  def initialize
    @quote = <<-QUOTESTR.gsub(/^ {6}/,'')
      If you could kick the person
      in the pants responsible for
      most of your trouble, you
      wouldn't sit for a month.
              - Theodore Roosevelt
      QUOTESTR
  end

  def cite
    puts @quote
  end
end

q = Quote.new
q.cite

I also found a Ruby unindent gem that cleans up the leading spaces without having to know the number of spaces to remove in the gsub call. You can call it with just QUOTESTR.unindent.

Happing coding.

–Chris