Read more

Ruby: Removing leading whitespace from HEREDOCs

Henning Koch
March 19, 2015Software engineer at makandra GmbH

If you're on Ruby 2.3+ there's a <<~ operator to automatically unindent HEREDOCs:

str = <<~MESSAGE
  Hello Universe!
  This is me.
             Bye!
MESSAGE
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

If you have an older Ruby, you can use the String#strip_heredoc Show archive.org snapshot method from ActiveSupport. See Summarizing heredoc in ruby and rails for an example.

Technically, it looks for the least indented line in the whole string, and removes that amount of leading whitespace.

Posted by Henning Koch to makandra dev (2015-03-19 08:40)