在 Ruby 中分解多行上的长字符串而不剥离换行符 [英] Breaking up long strings on multiple lines in Ruby without stripping newlines

查看:136
本文介绍了在 Ruby 中分解多行上的长字符串而不剥离换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

  • HEREDOC
  • %Q{}
  • 实际的字符串连接.

然而,所有这些情况最终都需要更多的计算周期,这看起来很愚蠢.字符串连接很明显,但是对于 HEREDOC%Q 我必须去掉换行符,通过类似 .gsub(/\n$/, '').

However, all of these cases end up taking more computation cycles, which seems silly. String concatenation obviously, but for HEREDOC and %Q I have to strip out the newlines, via something like .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.

示例:

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

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

I find the above a bit hard to read.

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

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

推荐答案

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

Three years later, there is now a solution in Ruby 2.3: The squiggly 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

博文链接:https://infinum.co/the-capsized-8/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.

这篇关于在 Ruby 中分解多行上的长字符串而不剥离换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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