Ruby元编程 - 多行字符串,不试图评估内部#{}

时间:2012-10-18 21:25:21

标签: ruby metaprogramming multiline

有没有办法让多行字符串不试图评估内部#{} ?

我想要以下内容:

doc <<-DOC    
    describe "should get sysdate on test: #{test_name}" do
        it "should get SYSDATE" do
            conx_bd.sysdate.should_not == NULL
        end
    end    
DOC

使用此内容创建字符串(doc):(用于元编程)

describe "should get sysdate on test: #{test_name}" do
    it "should get SYSDATE" do
        conx_bd.sysdate.should_not == NULL
    end
end    

我收到了这个错误:

NameError: undefined local variable or method `test_name' for main:Object

如果使用单引号包围heredoc标识符,如果字符串具有例如require

,则会出现此错误
doc <<'-DOC'
require "spec_helper.rb" # conexión oracle

describe "should get sysdate on test: #{test_name}" do
    it "should get SYSDATE" do
        conx_bd.sysdate.should_not == NULL
    end
end  

DOC

错误:

LoadError: no such file to load -- spec_helper

TKS

编辑: 请大家帮忙,我从答案中得到2个可能的解决方案。

首先我定义多行字符串

时出错
doc <<-DOC should be <<-doc 
  1. scape#with \

    &LT;&LT; -doc
        描述“应该在测试时获取sysdate:#{test_name}”         它“应该得到SYSDATE”             conx_bd.sysdate.should_not == NULL         结束     结束
    文档

  2. 用单引号

    包围heredoc标识符

    &LT;&LT; - 'doc的'
        描述“应该在测试时获取sysdate:#{test_name}”         它“应该得到SYSDATE”         conx_bd.sysdate.should_not == NULL         结束     结束
    文档

2 个答案:

答案 0 :(得分:3)

用单引号括住heredoc标识符。

doc <<-'DOC'    
    describe "should get sysdate on test: #{test_name}" do
        it "should get SYSDATE" do
            conx_bd.sysdate.should_not == NULL
        end
    end    
DOC

编辑我对单引号开头和连字符的相对位置有误。 steenslag是对的。固定的。

答案 1 :(得分:2)

在#之前尝试使用转义字符。转义字符为\