多行字串

建立多行字串的最簡單方法是在引號之間使用多行:

address = "Four score and seven years ago our fathers brought forth on this
continent, a new nation, conceived in Liberty, and dedicated to the
proposition that all men are created equal."

該技術的主要問題是,如果字串包含引號,它將破壞字串語法。要解決此問題,你可以使用 heredoc

puts <<-RAVEN
  Once upon a midnight dreary, while I pondered, weak and weary, 
  Over many a quaint and curious volume of forgotten lore— 
      While I nodded, nearly napping, suddenly there came a tapping, 
  As of some one gently rapping, rapping at my chamber door. 
  "'Tis some visitor," I muttered, "tapping at my chamber door— 
              Only this and nothing more." 
  RAVEN

Ruby 使用 <<EOT 支援 shell 樣式的文件,但是終止文字必須從行開始。這搞砸了程式碼縮排,因此沒有太多理由使用該樣式。不幸的是,字串將有縮排,這取決於程式碼本身是如何縮排的。

Ruby 2.3 通過引入 <<~解決了這個問題,<<~去除了多餘的前導空格:

Version >= 2.3

def build_email(address)
  return (<<~EMAIL)
    TO: #{address}

    To Whom It May Concern:

    Please stop playing the bagpipes at sunrise!
                     
    Regards,
    Your neighbor               
  EMAIL
end

百分比字串也可用於建立多行字串:

%q(
HAMLET        Do you see yonder cloud that's almost in shape of a camel?
POLONIUS        By the mass, and 'tis like a camel, indeed.
HAMLET        Methinks it is like a weasel.
POLONIUS        It is backed like a weasel.
HAMLET        Or like a whale?
POLONIUS        Very like a whale
)

有幾種方法可以避免插值和轉義序列:

  • 單引號而不是雙引號:'\n is a carriage return.'

  • 小寫字串 q%q[#{not-a-variable}]

  • 單引號 heredoc 中的終端字串:

    <<-'CODE'
       puts 'Hello world!'
    CODE