ruby - 如何从 Ruby HEREDOC 中删除前导空白字符?

标签 ruby whitespace heredoc

我在尝试制作 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/

相关文章:

javascript - 在 JavaScript 中创建多行字符串

mysql在使用heredoc时提示输入密码

Ruby:方法莫名其妙地被覆盖并设置为零

Ruby 使用 JSON 序列化结构

ruby - 优雅的链式 'or' 用于测试 Ruby 中的相同变量

HTML 等同于......确实会中断;

java - 空格匹配正则表达式 - Java

ruby - 在 Sinatra 中获取唯一的 session ID

css - 为什么我的网站一侧有多余的空白区域?

bash - 如何在bash脚本中运行sqlite3?