Ruby:我可以编写没有连接的多行字符串吗? [英] Ruby: Can I write multi-line string with no concatenation?

查看:62
本文介绍了Ruby:我可以编写没有连接的多行字符串吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法使它看起来更好一点?

Is there a way to make this look a little better?

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'

就像,有没有一种暗示串联的方法?

Like, is there a way to imply concatenation?

推荐答案

此答案有很多方面可以帮助我获得所需的信息(轻松的多行连接,无需多余的空格),但是由于没有实际答案,我在这里编译它们:

There are pieces to this answer that helped me get what I needed (easy multi-line concatenation WITHOUT extra whitespace), but since none of the actual answers had it, I'm compiling them here:

str = 'this is a multi-line string'\
  ' using implicit concatenation'\
  ' to prevent spare \n\'s'

=> "this is a multi-line string using implicit concatenation to eliminate spare
\\n's"

作为奖励,这是一个使用有趣的HEREDOC语法的版本(通过此链接):

As a bonus, here's a version using funny HEREDOC syntax (via this link):

p <<END_SQL.gsub(/\s+/, " ").strip
SELECT * FROM     users
         ORDER BY users.id DESC
END_SQL
# >> "SELECT * FROM users ORDER BY users.id DESC"

后者主要用于需要的情况在处理上更具灵活性。我个人不喜欢它,这样会使处理过程变得奇怪。字符串(即,位于字符串前面,但使用通常在后面的实例方法),但是它在那里。请注意,如果要缩进最后一个 END_SQL 标识符(这很常见,因为它可能在函数或模块内部),则需要使用带连字符的语法(即, p<< -END_SQL 而不是 p<<< END_SQL )。否则,缩进空格会导致标识符被解释为字符串的延续。

The latter would mostly be for situations that required more flexibility in the processing. I personally don't like it, it puts the processing in a weird place w.r.t. the string (i.e., in front of it, but using instance methods that usually come afterward), but it's there. Note that if you are indenting the last END_SQL identifier (which is common, since this is probably inside a function or module), you will need to use the hyphenated syntax (that is, p <<-END_SQL instead of p <<END_SQL). Otherwise, the indenting whitespace causes the identifier to be interpreted as a continuation of the string.

这不会节省太多的键入内容,但看起来比使用+号更好,

This doesn't save much typing, but it looks nicer than using + signs, to me.

另外(我在几年后的编辑中说),如果您使用的是Ruby 2.3+,则运算符<<〜也可用,它从最终字符串中删除了多余的缩进。在这种情况下,您应该可以删除 .gsub 调用(尽管它可能取决于起始缩进和最终需求)。

Also (I say in an edit, several years later), if you're using Ruby 2.3+, the operator <<~ is also available, which removes extra indentation from the final string. You should be able to remove the .gsub invocation, in that case (although it might depend on both the starting indentation and your final needs).

编辑:添加一个:

p %{
SELECT * FROM     users
         ORDER BY users.id DESC
}.gsub(/\s+/, " ").strip
# >> "SELECT * FROM users ORDER BY users.id DESC"

这篇关于Ruby:我可以编写没有连接的多行字符串吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆