How do I remove leading whitespace chars from Ruby HEREDOC?

后端 未结 11 707
误落风尘
误落风尘 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:50

    Like the original poster, I too discovered the <<-HEREDOC syntax and was pretty damn disappointed that it didn't behave as I thought it should behave.

    But instead of littering my code with gsub-s I extended the String class:

    class String
      # Removes beginning-whitespace from each line of a string.
      # But only as many whitespace as the first line has.
      #
      # Ment to be used with heredoc strings like so:
      #
      # text = <<-EOS.unindent
      #   This line has no indentation
      #     This line has 2 spaces of indentation
      #   This line is also not indented
      # EOS
      #
      def unindent
        lines = []
        each_line {|ln| lines << ln }
    
        first_line_ws = lines[0].match(/^\s+/)[0]
        re = Regexp.new('^\s{0,' + first_line_ws.length.to_s + '}')
    
        lines.collect {|line| line.sub(re, "") }.join
      end
    end
    

提交回复
热议问题