多行字符串

创建多行字符串的最简单方法是在引号之间使用多行:

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