Ruby将自动连接相邻的两个字符串:
foo = 'a' 'b'
foo # => "ab"
foo = 'a'
'b'
foo # => "a"
因此,您不能简单地打破行并期望Ruby弄清楚该怎么做。
\
将该行标记为继续,因此您可以使用以下命令:
foo = "a" \
"b"
foo # => "ab"
或者,依靠 +
字符串拼接:
foo = 'a' +
'b'
foo # => "ab"
我会建议使用加号+
,因为它通常用于连接字符串,所以其含义非常明显。使用反斜杠\
会导致人们将非常长的表达式连接起来而不是分解它们。
如果你的字符串非常长,你可以使用一些其他的技巧:
foo = [
'foo',
'bar'
].join
foo # => "foobar"
foo = [
'foo',
'bar'
].join(' ')
foo # => "foo bar"
或者:
foo = [
'foo',
'bar'
] * ' '
foo # => "foo bar"
long_str = 'This is a veeeeeeeryyyyyy' +
' looooonggggg string'
path = "//div/p[contains(., '#{ long_str }')]"
或者:
long_str = [
'This is a veeeeeeeryyyyyy',
'looooonggggg string'
].join(' ')
path = "//div/p[contains(., '%s')]" % long_str
您可以使用反斜杠来表示字符串在下一行继续,如下所示:
str = "this is a long \
string"
print str # => this is a long string
str = <<HEREDOC
This is my string :)
Let's imbue code in the imbued doc: #{[4, 2, 3, 1].sort}
HEREDOC
print str
# => This is my string :)
# => Let's imbue code in the imbued doc: [1, 2, 3, 4]
< p > HEREDOC
可以是您想要的任何名称。您可以在此处了解有关此类文档的更多信息。