__END__ 之后 DATA 的 Ruby 范围 [英] Ruby scope of DATA after __END__

查看:43
本文介绍了__END__ 之后 DATA 的 Ruby 范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将这个 Ruby 技巧与 __END__DATA 结合使用,将一些数据放入我的程序文件中:

I'm using this Ruby trick with __END__ and DATA to put some data inside my program file:

class Foo
  def initialize()
    puts DATA.read.inspect
  end
end
puts DATA.read.inspect
Foo.new
__END__
test

这会生成以下输出:

"test"
""

我曾假设 DATA 将在全局范围内相同,但在类内部它没有内容.我如何在类中的 __END__ 之后访问数据(除了使用全局变量的明显和丑陋的解决方案)?

I had assumed DATA would be the same globally, but inside the class it has no content. How would I get access to the data after __END__ inside a class (apart from the obvious and ugly solution using global variables)?

添加:我看到两次阅读 DATA 是如何让我第二次没有任何结果的.我可以使用 rewind 回到起点,但是 read 然后给了我程序的完整源代码.在 __END__ 之后的后续使用 DATA 之后,是否有更简单的方法来获取部分,或者我最好阅读一次并将其存储在其他地方以备将来使用?

ADDED: I see how reading DATA twice gives me nothing the second time. I could use rewind to get back to the start, but read then gives me the entire source code of my program. Is there an easier way to get to just the part after __END__ on subsequent uses of DATA, or would I be better of reading it once and storing it somewhere else for future use?

推荐答案

DATA 是一样的.如果不是执行 Foo.new,而是第二次执行 DATA.read,您将获得相同的输出.

DATA is the same. You would get the same output if instead of doing Foo.new you would do DATA.read a second time.

这是因为在第一次读取 DATA(这是一个 IO)后已经到达流的末尾,所以任何进一步的读取都将返回一个空字符串,除非您将额外的数据附加到 DATA 或倒带 DATA 到流的开头.

This is because after the first read DATA (which is an IO) has reached the end of the stream, so any further reads will return an empty string, unless you append additional data to DATA or rewind DATA to the beginning of the stream.

要在 __END__ 之后立即返回原点,您必须在对 DATA 执行任何读取之前阅读 DATA.pos 和然后在读取后将 pos 恢复为该值.最简单的解决方案可能只是在脚本的开头执行 FOO = DATA.read,然后使用 FOO.

To seek back to the point right after the __END__ you have to read DATA.pos before performing any reading on DATA and then restore pos to that value after reading. The easiest solution is probably just doing FOO = DATA.read at the beginning of the script and then using FOO.

这篇关于__END__ 之后 DATA 的 Ruby 范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆