docwhat's avatardocwhat's blog

Unindenting HEREDOCs in Ruby

This is a bit of code I wanted to save.

When using HEREDOCs in Ruby, the <<- operator is handy to keep everything indented in the source. But it doesn’t help with the content of the HEREDOC.

Example:

def example
  puts <<-EOF
This is left.

  This is indented two.
  EOF
end

In rails, you can do this:

def example
  puts <<-EOF.strip_heredoc
    This is left.

      This is indented two.
  EOF
end

There’s a helpful Stack Overflow question on this, in fact.

Here’s a simplish solution for plain ‘ol Ruby:

def unindent(string)
  first = string[/As*/]
  string.gsub(/^#{Regexp.quote first}/, '')
end

def example
  puts unindent(<<-EOF)
    This is flush left.

      This is indented by two spaces
  EOF
end

Too bad you can’t pull in some of these Rails monkey patches without pulling in lots of stuff you don’t want.

Edit on GitHub