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

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'

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


当前回答

多行字符串有多种语法,你已经读过了。我最喜欢的是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”行都包含前导空白,因为它们在代码中的缩进。如果不需要这个空格,那么您必须像现在这样使用连接的字符串。

其他回答

在ruby 2.0中,你现在可以只使用%

例如:

    SQL = %{
      SELECT user, name
      FROM users
      WHERE users.id = #{var}
      LIMIT #{var2}
    }
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'

<<是字符串的连接操作符

像你一样,我也在寻找一个不包括换行符的解决方案。(虽然它们在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 = <<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

最近,随着Ruby 2.3的新特性,新的弯弯曲曲的HEREDOC将允许您以一种非常好的方式编写多行字符串,并且只需要进行最小的更改,因此,将它与.squish(如果您正在使用rails)结合使用将使您以一种非常好的方式编写多行字符串! 在只使用ruby的情况下,您可以执行<<~SQL.split。Join(" "),几乎相同

[1] pry(main)> <<~SQL.squish
[1] pry(main)*   select attr1, attr2, attr3, attr4, attr5, attr6, attr7
[1] pry(main)*   from table1, table2, table3, etc, etc, etc, etc, etc,
[1] pry(main)*   where etc etc etc etc etc etc etc etc etc etc etc etc etc
[1] pry(main)* SQL
=> "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"

裁判:https://infinum.co/the-capsized-eight/multiline-strings-ruby-2-3-0-the-squiggly-heredoc