I\'m having a problem with a Ruby heredoc i\'m trying to make. It\'s returning the leading whitespace from each line even though i\'m including the - operator, which is supp
If you're using Rails 3.0 or newer, try #strip_heredoc. This example from the docs prints the first three lines with no indentation, while retaining the last two lines' two-space indentation:
if options[:usage]
puts <<-USAGE.strip_heredoc
This command does such and such.
Supported options are:
-h This message
...
USAGE
end
The documentation also notes: "Technically, it looks for the least indented line in the whole string, and removes that amount of leading whitespace."
Here's the implementation from active_support/core_ext/string/strip.rb:
class String
def strip_heredoc
indent = scan(/^[ \t]*(?=\S)/).min.try(:size) || 0
gsub(/^[ \t]{#{indent}}/, '')
end
end
And you can find the tests in test/core_ext/string_ext_test.rb.