我在尝试制作 Ruby heredoc 时遇到问题。它从每一行返回前导空格,即使我包括 - 运算符,它应该抑制所有前导空格字符。我的方法是这样的:
def distinct_count
<<-EOF
\tSELECT
\t CAST('#{name}' AS VARCHAR(30)) as COLUMN_NAME
\t,COUNT(DISTINCT #{name}) AS DISTINCT_COUNT
\tFROM #{table.call}
EOF
end
我的输出是这样的:
=> " \tSELECT\n \t CAST('SRC_ACCT_NUM' AS VARCHAR(30)) as
COLUMN_NAME\n \t,COUNT(DISTINCT SRC_ACCT_NUM) AS DISTINCT_COUNT\n
\tFROM UD461.MGMT_REPORT_HNB\n"
当然,这在这个特定实例中是正确的,除了第一个 "和\t 之间的所有空格。有人知道我在这里做错了什么吗?
最佳答案
<<-
heredoc 的形式只忽略结束分隔符的前导空格。
在 Ruby 2.3 及更高版本中,您可以使用波浪形的 heredoc ( <<~
) 来抑制内容行的前导空格:
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"
来自 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.
关于ruby - 如何从 Ruby HEREDOC 中删除前导空白字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3772864/