【问题标题】:Ruby multiline string like PHP nowdoc?像 PHP nowdoc 这样的 Ruby 多行字符串?
【发布时间】:2014-03-26 08:29:33
【问题描述】:

在 Ruby 中可以有多行字符串,就像 PHP 的 nowdoc [1]

例如

puts '

\\foo

'

我想输出以下没有转义的内容

\\foo

[1] Nowdocs 对于单引号字符串,就像 heredocs 对于双引号字符串一样。 nowdoc 的指定与heredoc 类似,但在nowdoc 内部不进行解析。 http://hk1.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc

【问题讨论】:

    标签: ruby


    【解决方案1】:

    literals documentation 中所述,您只需在heredoc 标识符周围加上单引号,如下所示:

    puts <<'EOS'
    #{variable}
    \\escaped
    EOS
    

    输出:

    #{variable}
    \\escaped
    

    【讨论】:

      【解决方案2】:

      在 heredoc 分隔符周围加上单引号:

      > tmp = "hi"
      > s = <<'EOS'
      ' #{tmp}
      ' \\foo
      ' EOS
      => "\#{tmp}\n\\\\foo\n"
      > puts s
      #{tmp}
      \\foo
      

      【讨论】:

        【解决方案3】:
        2.1.0 :001 > %q{
        2.1.0 :002'> my
        2.1.0 :003'> single
        2.1.0 :004'> quoted
        2.1.0 :005'> multiline
        2.1.0 :006'> string
        2.1.0 :007'> }
         => "\nmy\nsingle\nquoted\nmultiline\nstring\n" 
        
        2.1.0 :008 > %Q{
        2.1.0 :009"> my
        2.1.0 :010"> double
        2.1.0 :011"> quoted
        2.1.0 :012"> multiline
        2.1.0 :013"> string
        2.1.0 :014"> }
         => "\nmy\ndouble\nquoted\nmultiline\nstring\n"
        

        更多信息http://simpleror.wordpress.com/2009/03/15/q-q-w-w-x-r-s/

        【讨论】:

          猜你喜欢
          • 2015-03-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-02
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多