如何在Ruby语法中将字符串分成两行

3
如何在Ruby代码中将字符串分成两行?有没有特定的符号?
def my_def
  path = "//div/p[contains(., 'This is a veeeeeeeryyyyyy looooonggggg string')]"
end

我希望做出类似这样的东西:

def my_def
  path = "//div/p[contains(., 'This is a veeeeeeeryyyyyy
          looooonggggg string')]"
end

enter image description here 反斜杠不起作用!


在Pry中做这个有些困难。尝试在纯文本编辑器中编写,并从控制台运行它。 - JLB
请不要使用图片来展示问题中的重要信息。我们无法复制/粘贴这些信息,搜索引擎也无法索引它们以帮助他人找到您的问题。此外,链接会失效和破损。相反,请将信息复制/粘贴到您的问题中。 - the Tin Man
2个回答

8

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

3

您可以使用反斜杠来表示字符串在下一行继续,如下所示:

str = "this is a long \
string"

print str # => this is a long string

如果你的字符串变得过于庞大,使用Here Docs 可能是一个不错的想法。它们允许你在代码中间编写文本块:
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 可以是您想要的任何名称。您可以在此处了解有关此类文档的更多信息。


反斜杠不像我预期的那样工作!作为示例,我给你附上了一张图片。 - andgursky
@andgursky 你试过用反斜杠运行代码了吗?你展示的图片看起来像是你使用的高亮程序的一个错误,但是这个程序应该可以正常运行。 - SlySherZ

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