如何从 Ruby HEREDOC 中删除前导空白字符? [英] How do I remove leading whitespace chars from Ruby HEREDOC?

查看:55
本文介绍了如何从 Ruby HEREDOC 中删除前导空白字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试制作 Ruby 继承文件时遇到了问题.它从每一行返回前导空格,即使我包括 - 运算符,它应该抑制所有前导空格字符.我的方法是这样的:

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
        \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 之间的所有空格.有人知道我在这里做错了什么吗?

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

推荐答案

heredoc 的 <<- 形式只忽略结尾分隔符的前导空格.

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

在 Ruby 2.3 及更高版本中,您可以使用波浪形的 heredoc (<<~) 来抑制内容行的前导空格:

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"

来自 Ruby 文字文档:

最小缩进行的缩进将从每个内容的行.请注意,空行和单独组成的行文字制表符和空格将被忽略的目的确定缩进,但考虑转义的制表符和空格非缩进字符.

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 HEREDOC 中删除前导空白字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆