Ruby: Removing leading whitespace from HEREDOCs

Updated . Posted . Visible to the public.

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

str = <<~MESSAGE
  Hello Universe!
  This is me.
             Bye!
MESSAGE

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.

Henning Koch
Last edit
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2015-03-19 07:40)