有什么办法能让这看起来好一点吗?
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'
比如,有没有办法暗示串联?
有什么办法能让这看起来好一点吗?
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"
其他回答
多行字符串有多种语法,你已经读过了。我最喜欢的是perl风格:
conn.exec %q{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}
多行字符串以%q开头,后面跟着一个{、[或(,然后以相应的反转字符结束。%q不允许插值;%Q是这样的,所以你可以这样写:
conn.exec %Q{select attr1, attr2, attr3, attr4, attr5, attr6, attr7
from #{table_names},
where etc etc etc etc etc etc etc etc etc etc etc etc etc}
我不知道这些多行字符串是怎么叫的我们就叫它们Perl multilines吧。
但是请注意,无论您使用的是Perl多行还是像Mark和Peter建议的那样使用heredocs,最终都会出现潜在的不必要的空格。在我的例子和他们的例子中,“from”和“where”行都包含前导空白,因为它们在代码中的缩进。如果不需要这个空格,那么您必须像现在这样使用连接的字符串。
是的,如果你不介意额外的换行被插入:
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'
你也可以使用heredoc:
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
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"