有什么办法能让这看起来好一点吗?

conn.exec 'select attr1, attr2, attr3, attr4, attr5, attr6, attr7 ' +
          'from table1, table2, table3, etc, etc, etc, etc, etc, ' +
          'where etc etc etc etc etc etc etc etc etc etc etc etc etc'

比如,有没有办法暗示串联?


当前回答

为了避免每一行的圆括号关闭,你可以简单地使用双引号和反斜杠来转义换行:

"select attr1, attr2, attr3, attr4, attr5, attr6, attr7 \
from table1, table2, table3, etc, etc, etc, etc, etc, \
where etc etc etc etc etc etc etc etc etc etc etc etc etc"

其他回答

像你一样,我也在寻找一个不包括换行符的解决方案。(虽然它们在SQL中可能是安全的,但在我的情况下不安全,我有一个大的文本块要处理)

这可以说是同样丑陋,但你可以在heredoc中反斜杠转义换行符,以从结果字符串中省略它们:

conn.exec <<~END_OF_INPUT
    select attr1, attr2, attr3, attr4, attr5, attr6, attr7 \
    from table1, table2, table3, etc, etc, etc, etc, etc, \
    where etc etc etc etc etc etc etc etc etc etc etc etc etc
  END_OF_INPUT

请注意,如果没有插值(即<<~'END_OF_INPUT'),就不能执行此操作,所以要小心。#{expressions}将在这里求值,而在原始代码中不会求值。答:出于这个原因,威尔逊的回答可能更好。

如果你不介意额外的空格和换行,你可以使用

conn.exec %w{select attr1, attr2, attr3, attr4, attr5, attr6, attr7
  from table1, table2, table3, etc, etc, etc, etc, etc,
  where etc etc etc etc etc etc etc etc etc etc etc etc etc} * ' '

(使用%W表示插值字符串)

为了避免每一行的圆括号关闭,你可以简单地使用双引号和反斜杠来转义换行:

"select attr1, attr2, attr3, attr4, attr5, attr6, attr7 \
from table1, table2, table3, etc, etc, etc, etc, etc, \
where etc etc etc etc etc etc etc etc etc etc etc etc etc"
conn.exec = <<eos
  select attr1, attr2, attr3, attr4, attr5, attr6, attr7
  from table1, table2, table3, etc, etc, etc, etc, etc,
  where etc etc etc etc etc etc etc etc etc etc etc etc etc
eos

其他选项:

#multi line string
multiline_string = <<EOM
This is a very long string
that contains interpolation
like #{4 + 5} \n\n
EOM

puts multiline_string

#another option for multiline string
message = <<-EOF
asdfasdfsador #{2+2} this month.
asdfadsfasdfadsfad.
EOF

puts message