在 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
知道我怎样才能做到这一点吗?
已经有评论指出该错误无法确认,Babai 还发布了工作示例。
也许你还有另一个问题:
DATA对应后面的文字__END__
of the main文档,而不是实际的源代码文件。
有用:
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__
在库中,仅作为主文件的一部分。
- 请使用此处文档 - 或将数据存储在外部数据文件中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)