How do I remove leading whitespace chars from Ruby HEREDOC?

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

    The <<- form of heredoc only ignores leading whitespace for the end delimiter.

    With Ruby 2.3 and later you can use a squiggly heredoc (<<~) to suppress the leading whitespace of content lines:

    def test
      <<~END
        First content line.
          Two spaces here.
        No space here.
      END
    end
    
    test
    # => "First content line.\n  Two spaces here.\nNo space here.\n"
    

    From the Ruby literals documentation:

    The indentation of the least-indented line will be removed from each line of the content. Note that empty lines and lines consisting solely of literal tabs and spaces will be ignored for the purposes of determining indentation, but escaped tabs and spaces are considered non-indentation characters.

提交回复
热议问题