gem install dedent
Tested with Ruby 1.9.3 and 2.1.1.
This is a tiny gem that adds the
dedent method to String. This method strips leading whitespace from each
line, preserving indentation. So, the line with the least amount of leading whitespace will have all leading
whitespace removed, while other lines will have whitespace relative to that line's offset.
The main use of this is with heredocs. It can be annoying because even with the
<<- form, all the initial
whitespace on each line of the string is preserved, so if you keep the string in the same indentation as the
code, you end up with extra space.
Here's an example of using dedent with heredocs:
foo variable contains the following string:
One thing to note is that lines with no non-whitespace characters are not considered when determining the indentation of a text block:
"\n foo".dedent # => "\nfoo"
This project is release under the MIT License.