Ruby 中有类似空流的东西吗?
我可以在 Unix 系统上使用:
File.open('/dev/null', 'w')
,但如果有 Ruby 方法可以实现这一点,我想使用它。我只是在寻找一个 I/O 流,它会立即“丢弃”所有写入,有点像空对象。
I could use:
File.open('/dev/null', 'w')
on Unix systems, but if there is a Ruby way to achieve this, I'd like to use it. I am just looking for an I/O stream, that immediately "trashes" all writes, kind of like a null-object.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您想要流的完整行为,最好的方法可能是使用:
请注意,
File::NULL
是 Ruby 1.9.3 中的新增功能;你可以使用我的backports
gem:你也可以复制 相关代码(如果您愿意)。
If you want the full behavior of streams, the best is probably to use:
Note that
File::NULL
is new to Ruby 1.9.3; you can use mybackports
gem:You could also copy the relevant code if you prefer.
有 stringIO,当我想引入虚拟文件流时,我发现它很有用:
下面是来自 heckle 的一些代码,它可以找到适用于 Unix 和 Windows 的位桶,稍作修改:
There's stringIO, which I find useful when I want to introduce a dummy filestream:
And here's some code from heckle that finds the bit bucket for both Unix and Windows, slightly modified:
不,我不相信 Ruby 中存在类似空流的东西,至少在早期版本中是这样。在这种情况下,您必须自己制作一个。根据它将调用的方法,您需要编写
空流类上的存根方法,如下所示:
上面的示例绝不完整。例如,某些流可能需要调用 write、puts 或其他方法。此外,某些方法应该通过在其方法中返回
self
来实现,例如<<
,而其他方法则不然。No, I don't believe there is anything like a null stream in Ruby, at least in earlier versions. In that case, you must make one yourself. Depending on the methods that it will call, you will need to write
stub methods on the null stream class, like this:
The above example is by no means complete. For example, some streams may require calling the
write
,puts
or other methods. Moreover, some methods should be implemented by returningself
in their methods, like<<
, others not.Logger.new("/dev/null")
就可以了Logger.new("/dev/null")
does the trick有一个名为 devnull 的 gem
它不与空文件交互,而是为 IO 对象实现的所有方法提供虚拟方法。
There's a gem called devnull
It doesn't interact with the null file, but instead has dummy methods for all the methods that IO objects implement.