You are using an outdated browser which puts all net citizens at risk. As an incentive to upgrade to a current and thus much more secure product (we recommend the free Firefox browser), you won't be able to visit this site in its cute design, but in this rather boring printer-ready version only. Thank you for considering a browser update!

Heredoc with Indent in Ruby

Heredocs come in handy when you have to deal with larger multi-line strings in the source code itself. However, it usually breaks the indents:

class Poem
  def initialize
    @text = <<END
"Faith" is a fine invention
When Gentlemen can see
But Microscopes are prudent
           In an Emergency.
(Emily Dickinson 1830-1886)
END
  end
  def recite
    puts @text
  end
end

But it wouldn’t be Ruby if there were no way to make this pretty. The minus in -END makes sure any whitespace before the end marker is ignored and the first six spaces of every line are cut when the string collected by heredoc is post processed with gsub:

class Poem
  def initialize
    @text = <<-END.gsub(/^ {6}/, '')
      "Faith" is a fine invention
      When Gentlemen can see
      But Microscopes are prudent
                 In an Emergency.
      (Emily Dickinson 1830-1886)
    END
  end
  def recite
    puts @text
  end
end

The result for both snippets is exactly the same – provided you stick to the recommended 2 spaces indent for Ruby source code:

>> Poem.new.recite
"Faith" is a fine invention
When Gentlemen can see
But Microscopes are prudent
           In an Emergency.
(Emily Dickinson 1830-1886)

(Sven Schwyn)

Comments

Markus H. said on Thursday, January 28, 2010:

Thank you, exactly what I was searching for! Furthermore I didn’t know the <<END.method trick.

Adriano said on Thursday, January 27, 2011:

Instead of #gsub(/^ {6}/, ’’), you could have required the gem heredoc_unindent and called simply #unindent. Besides being more concise, that would generalize better, given that the indentation level would not have had to be specified manually. You can find the gem at http://rubygems.org/gems/heredoc_unindent

(We are remaking our web presence and therefore comments are temporary disabled.)