How do I remove leading whitespace chars from Ruby HEREDOC?

后端 未结 11 706
误落风尘
误落风尘 2020-11-28 22:09

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

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 22:43

    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.

提交回复
热议问题