说我希望有一个非常大的漂亮打印的html代码段与我的ruby代码内联.什么是最干净的方法来做到这一点,而不会丢失我的字符串中的任何格式或不得不记住某种gsub正则表达式.
将它们编码为一行很容易,但很难阅读:
1.times do
  # Note that the spaces have been changed to _ so that they are easy to see here.
  doc = "\n<html>\n__<head>\n____<title>\n______Title\n____</title>\n__</head>\n__<body>\n____Body\n__</body>\n</html>\n"
  ans = "Your document: %s" % [doc]
  puts ans
end
ruby中的多行文本更容易阅读,但字符串不能与其余代码一起缩进:
1.times do
  doc = "
<html>
  <head>
    <title>
      Title
    </title>
  </head>
  <body>
    Body
  </body>
</html>
"
  ans = "Your document: %s" % [doc]
  puts ans
end
例如,以下是我的代码缩进,但字符串现在每行前面有四个额外的空格:
1.times do
  doc = <<-EOM
    <html>
      <head>
        <title>
          Title
        </title>
      </head>
      <body>
        Body
      </body>
    </html>
  EOM
  ans = "Your document: %s" % [doc]
  puts ans
end
大多数人都使用上面的HEREDOC代码,并对结果进行正则表达式替换,以便在每行的开头取出额外的空格.我想要一种方式,我不必每次都要经历复兴的麻烦.
ens*_*ens 21
从Ruby 2.3开始,<<~heredoc剥离了领先的内容空白:
def make_doc(body)
  <<~EOF
  <html>
    <body>
      #{body}
    </body>
  </html>
  EOF
end
puts make_doc('hello')
对于较旧的Ruby版本,以下内容比其他答案中提供的解决方案更详细,但几乎没有性能开销.它与单个长字符串文字一样快:
def make_doc(body)
  "<html>\n"       \
  "  <body>\n"     \
  "    #{body}\n"  \
  "  </body>\n"    \
  "</html>"
end
Cha*_*ell 20
string = %q{This
    is
        indented
  and
    has
         newlines}
下面是一些例子博客%q{},%Q{}别人和.
只要容易记住,就要把'Q'想象成"引号".
旁注: 从技术上讲,你在做报价时不需要'q'.
string = %{This
   also
      is indented
  and
     has
   newlines
      and handles interpolation like 1 + 1 = #{1+1}
}
但是,这是最佳实践,使用起来更具可读性%Q{}.
“|” 在 YAML 中,您可以创建可以缩进的多行字符串。仅当空格位于第一行第一个非空格字符之后的列中时,才计算空格。通过这种方式,您可以拥有具有缩进但也在代码中缩进的多行字符串。
require 'yaml'
1.times do
  doc = YAML::load(<<-EOM)
  |
     <html>
       <head>
         <title>
           Title
         </title>
       </head>
       <body>
         Body
       </body>
     </html>  
  EOM
  ans = "Your document: %s" % [doc]
  puts ans
end
| 归档时间: | 
 | 
| 查看次数: | 18161 次 | 
| 最近记录: |