Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

How do I remove leading whitespace chars from Ruby HEREDOC?

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 supposed to suppress all leading whitespace characters. my method looks like this:

    def distinct_count
    <<-EOF
        SELECT
         CAST('#{name}' AS VARCHAR(30)) as COLUMN_NAME
        ,COUNT(DISTINCT #{name}) AS DISTINCT_COUNT
        FROM #{table.call}
    EOF
end

and my output looks like this:

    => "            SELECT
             CAST('SRC_ACCT_NUM' AS VARCHAR(30)) as
COLUMN_NAME
            ,COUNT(DISTINCT SRC_ACCT_NUM) AS DISTINCT_COUNT

        FROM UD461.MGMT_REPORT_HNB
"

this, of course, is right in this specific instance, except for all the spaces between the first " and . does anyone know what i'm doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.
  Two spaces here.
No space here.
"

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...