Ruby:我能否使用无连接符的多行字符串?

498

有没有办法让这个看起来更好一些?

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'

比如说,有没有一种方式可以暗示字符串拼接?

17个回答

9
为了避免为每行代码都添加右括号,你可以使用双引号和反斜杠来转义换行符:
"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"

1
这是本页面上为数不多的实际回答问题的答案之一! - Josh

6
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'

<<是字符串连接运算符


3
+ 是常规的连接运算符,<<原地 追加运算符。在一个字面量上使用副作用确实可以起作用(第一个字符串被修改了两次并返回了),但是我认为这很奇怪,让我产生了疑惑,“+”则非常清晰明了。但也许这只是因为我对 Ruby 还不是很熟悉... - Beni Cherniavsky-Paskin
1
如果启用了frozen_string_literal,这将无法工作。 - Raido

6
如果您在意额外的空格和换行符,您可以使用。
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)

(在插值字符串中使用%W)


我非常喜欢这个,因为它允许更多的使用组合。 - schmijos
1
这将把多个相邻的空格压缩成一个。 (它在压缩换行符+后续缩进方面很有优势,但在行中间可能会令人惊讶。) - Beni Cherniavsky-Paskin

5
conn.exec [
  "select attr1, attr2, attr3, ...",
  "from table1, table2, table3, ...",
  "where ..."
].join(' ')

这个建议相较于here-documents和长字符串有一个优势,那就是自动缩进器可以适当地缩进字符串的每个部分。但这会带来效率上的损失。

1
@Aidan,你可以用反斜杠(类似于C语言)替换逗号,这样就不需要使用join(或数组)了:解释器将在(我想是)解析时连接字符串,使其比大多数替代方案更快。 但是,使用字符串数组连接的一个优点是,一些自动缩进程序比使用here-doc字符串或\更好。 - Wayne Conrad
1
一个注意点,heredoc语法<<-将允许适当的缩进。 - A. Wilson

5
今日优雅答案:
<<~TEXT
Hi #{user.name}, 

Thanks for raising the flag, we're always happy to help you.
Your issue will be resolved within 2 hours.
Please be patient!

Thanks again,
Team #{user.organization.name}
TEXT

“<<-TEXT”和“<<~TEXT”之间有区别,前者保留块内的空格,后者不保留。

还有其他选项,比如连接等,但总体而言这个更有意义。

如果我在这里说错了,请告诉我该怎么做...


Heredoc将包含换行符,这与原始代码不等价。 - Josh

4

和你一样,我也在寻找一种不包含换行符的解决方案。(虽然它们在 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},而它们在您的原始代码中不会被评估。出于这个原因,A. Wilson的回答可能更好。

0
你想在Ruby中使用多行吗?可以用三个引号来实现,同样也可以在Python中运行。
# to print multi line string

print("""
hello i am mario and this
is multi line it is same in python
""")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接