在Ruby中,在__END__
之后存储静态文本以便通过DATA
IO对象进行任意使用非常方便:
puts DATA.read # Prints "This is the stuff!"
__END__
This is the stuff!
但是,当我尝试从新类的上下文中引用DATA对象时,我会遇到意外错误(显然在Ruby 1.9.3和2.0中):
class Foo
STUFF = DATA.read # <class:Foo>: uninitialized constant Foo::DATA (NameError)
end
class Foo
STUFF = ::DATA.read # <class:Foo>: uninitialized constant DATA (NameError)
end
知道如何让这项工作成功吗?
答案 0 :(得分:8)
已有评论,错误无法确认,Babai也发布了工作实例。
也许你有另一个问题:
DATA对应主文档的__END__
后面的文字,而不是实际的源代码文件。
有效:
class Foo
STUFF = DATA
p STUFF.read
end
__END__
This is the stuff!
此处源代码文件与主文件相同。
但如果您将其存储为test_code.rb
并将其加载到主文件中:
require_relative 'test_code.rb'
然后你得到错误:
C:/Temp/test_code.rb:2:in `<class:Foo>': uninitialized constant Foo::DATA (NameError)
from C:/Temp/test_code.rb:1:in `<top (required)>'
from test.rb:1:in `require_relative'
from test.rb:1:in `<main>'
如果你的主文件是
require_relative 'test_code.rb'
__END__
This is the stuff!
然后这个过程适用于输出这就是东西!
回答你的问题:
__END__
,只能作为主文件的一部分。答案 1 :(得分:0)
好博客在这里: - Useless Ruby Tricks: DATA and END
这是有用的:
class Foo
def dis
DATA.read
end
end
Foo.new.dis # => "This is the stuff!\n"
__END__
This is the stuff!
class Foo
STUFF = DATA
p STUFF.read
end
__END__
This is the stuff!
# >> "This is the stuff!\n"
RUBY_VERSION # => "2.0.0"
class Foo
p STUFF = DATA.read
end
__END__
This is the stuff!
# >> "This is the stuff!\n"
答案 2 :(得分:0)
我倾向于使用File.read(__FILE__).split("\n__END__\n", 2)[1]
代替DATA.read