在 Ruby 中分解多行上的长字符串而不剥离换行符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10522414/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:22:32  来源:igfitidea点击:

Breaking up long strings on multiple lines in Ruby without stripping newlines

ruby-on-railsruby

提问by chug2k

We recently decided at my job to a ruby style guide. One of the edicts is that no line should be wider than 80 characters. Since this is a Rails project, we often have strings that are a little bit longer - i.e. "User X wanted to send you a message about Thing Y" that doesn't always fit within the 80 character style limit.

我们最近决定在我的工作中使用 ruby​​ 风格指南。其中一项法令是任何行的宽度都不应超过 80 个字符。由于这是一个 Rails 项目,所以我们经常有更长的字符串——即“用户 X 想给你发送一条关于事物 Y 的消息”,它并不总是适合 80 个字符的样式限制。

I understand there are three ways to have a long string span multiple lines:

我知道有三种方法可以让长字符串跨越多行:

  • HEREDOC
  • %Q{}
  • Actual string concatenation.
  • 赫里多克
  • %Q{}
  • 实际的字符串连接。

However, all of these cases end up taking more computation cycles, which seems silly. String concatenation obviously, but for HEREDOCand %QI have to strip out the newlines, via something like .gsub(/\n$/, '').

然而,所有这些情况最终都需要更多的计算周期,这似乎很愚蠢。显然是字符串连接,但是 forHEREDOC%Q我必须通过类似.gsub(/\n$/, '').

Is there a pure syntax way to do this, that is equivalent to just having the whole string on one line? The goal being, obviously, to not spend any extra cycles just because I want my code to be slightly more readable. (Yes, I realize that you have to make that tradeoff a lot...but for string length, this just seems silly.)

是否有一种纯粹的语法方式来做到这一点,相当于将整个字符串放在一行上?显然,目标是不要仅仅因为我希望我的代码更具可读性而花费任何额外的周期。(是的,我意识到您必须进行很多权衡……但是对于字符串长度,这似乎很愚蠢。)

Update: Backslashes aren't exactly what I want because you lose indentation, which really affects style/readability.

更新:反斜杠并不是我想要的,因为你失去了缩进,这确实影响了样式/可读性。

Example:

例子:

if foo
  string = "this is a \  
string that spans lines"  
end

I find the above a bit hard to read.

我觉得上面的内容有点难读。

EDIT: I added an answer below; three years later we now have the squiggly heredoc.

编辑:我在下面添加了一个答案;三年后,我们现在有了波浪形的heredoc。

采纳答案by chug2k

Three years later, there is now a solution in Ruby 2.3: The squiggly heredoc.

三年后,Ruby 2.3 现在有了一个解决方案:波浪形的 heredoc。

class Subscription
  def warning_message
    <<~HEREDOC
      Subscription expiring soon!
      Your free trial will expire in #{days_until_expiration} days.
      Please update your billing information.
    HEREDOC
  end
end

Blog post link: https://infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc

博文链接:https: //infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc

The indentation of the least-indented line will be removed from each line of the content.

缩进最少的行的缩进将从内容的每一行中删除。

回答by Jessehz

Maybe this is what you're looking for?

也许这就是你要找的?

string = "line #1"\
         "line #2"\
         "line #3"

p string # => "line #1line #2line #3"

回答by Emily

You can use \to indicate that any line of Ruby continues on the next line. This works with strings too:

您可以使用\来指示 Ruby 的任何行在下一行继续。这也适用于字符串:

string = "this is a \
string that spans lines"

puts string.inspect

will output "this is a string that spans lines"

会输出 "this is a string that spans lines"

回答by Zack Xu

I had this problem when I try to write a very long url, the following works.

当我尝试编写一个很长的 url 时遇到了这个问题,以下是有效的。

image_url = %w(
    http://minio.127.0.0.1.xip.io:9000/
    bucket29/docs/b7cfab0e-0119-452c-b262-1b78e3fccf38/
    28ed3774-b234-4de2-9a11-7d657707f79c?
    X-Amz-Algorithm=AWS4-HMAC-SHA256&
    X-Amz-Credential=ABABABABABABABABA
    %2Fus-east-1%2Fs3%2Faws4_request&
    X-Amz-Date=20170702T000940Z&
    X-Amz-Expires=3600&X-Amz-SignedHeaders=host&
    X-Amz-Signature=ABABABABABABABABABABAB
    ABABABABABABABABABABABABABABABABABABA
).join

Note, there must not be any newlines, white spaces when the url string is formed. If you want newlines, then use HEREDOC.

请注意,形成 url 字符串时不得有任何换行符、空格。如果您需要换行符,请使用 HEREDOC。

Here you have indentation for readability, ease of modification, without the fiddly quotes and backslashes on every line. The cost of joining the strings should be negligible.

在这里你有可读性的缩进,易于修改,每一行都没有繁琐的引号和反斜杠。加入字符串的成本应该可以忽略不计。

回答by iheggie

I modified Zack's answer since I wanted spaces and interpolation but not newlinesand used:

我修改了 Zack 的答案,因为我想要空格和插值而不是换行符并使用:

%W[
  It's a nice day "#{name}"
  for a walk!
].join(' ')

where name = 'fred'this produces It's a nice day "fred" for a walk!

其中,name = 'fred'这将产生It's a nice day "fred" for a walk!