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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章