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

问题:

We recently decided at my job to a ruby style guide.我们最近决定在我的工作中使用 ruby​​ 风格指南。 One of the edicts is that no line should be wider than 80 characters.其中一项法令是任何行的宽度都不应超过 80 个字符。 Since this is a Rails project, we often have strings that are a little bit longer - ie " User X wanted to send you a message about Thing Y " that doesn't always fit within the 80 character style limit.由于这是一个 Rails 项目,所以我们经常有更长的字符串——即“用户 X 想给你发送一条关于事物 Y 的消息”,它并不总是适合 80 个字符的样式限制。

I understand there are three ways to have a long string span multiple lines:我知道有三种方法可以让长字符串跨越多行:

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

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$/, '') .字符串连接很明显,但是对于HEREDOC%Q我必须通过类似.gsub(/\\n$/, '')东西.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。


解决方案:

参考一: https://en.stackoom.com/question/i9MM
参考二: https://stackoom.com/question/i9MM
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章