为什么我不能在类上下文中引用DATA?

问题描述 投票:4回答:3

在Ruby中,通过__END__ IO对象在DATA之后存储静态文本以供任意使用非常方便:

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

知道我怎么能做这个工作吗?

ruby
3个回答
8
投票

已有评论,错误无法确认,巴拜也发布了工作实例。

也许你有另一个问题:

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__,只能作为主文件的一部分。
  • 请使用Here-文档 - 或将数据存储在外部数据文件中。

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"

0
投票

我倾向于使用File.read(__FILE__).split("\n__END__\n", 2)[1]而不是DATA.read

© www.soinside.com 2019 - 2024. All rights reserved.