重新打开IO流与仅使用新流 [英] Reopening an IO Stream vs. just using the new Stream

查看:169
本文介绍了重新打开IO流与仅使用新流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby-Docs中,它提供了以下示例:

In the Ruby-Docs it gives the example of:

f1 = File.new("testfile")
f2 = File.new("testfile")
f2.readlines[0]   #=> "This is line one\n"
f2.reopen(f1)     #=> #<File:testfile>
f2.readlines[0]   #=> "This is line one\n"

我的问题是为什么要重新打开 f2 当你只能 f2.close f1.readlines [0] ?使用新流重新开放与仅使用新流有什么好处吗?

My question is why reopen f2 when you could just f2.close and f1.readlines[0]? Are there any advantages to reopening with a new stream vs. just using the new stream?

推荐答案

我在IRB上与一些开发者交谈过一段时间后,我得到的回应是,它主要用于更改 $ std 变量,以修改等方法放置打印输出到...

I talked to some devs on IRB a while back and the response I got was that it was mostly used for changing the $std variables to modify where methods such as puts and print output to...

$stdout.reopen(File.open('log'))
puts 'hello world'

使用它的原因而不是......

The reason for using this rather than...

$stdout = File.open('log')

...虽然有点悬而未决。我有一个开发人员说直接分配与ruby的一些C函数不匹配。我对C不太了解,也不能多说这个,但他给我指了一些 minitest source 查看正在使用的示例。然而,显然即使是消息来源已经切换到直接分配与重新开放,因为开发人员最后一次查看它。

...was kinda up in the air though. I had one dev that said that direct assignment didn't play well with some of ruby's C functions. I don't know much about C and can't say much about this, but he pointed me to some minitest source to see an example of it in use. However, apparently even the source has switched over to direct assignment vs. reopening since the dev last looked at it.

总之......从它的外观 IO #reopen 可能没用,但我很想听到反对的论点。

In conclusion... from the looks of it IO#reopen might be useless, but I would love to hear an argument against this.

更新

好的,所以我重新阅读文档,看到第二组选项重新打开

Ok, so I reread over the documentation and saw that there was a second set of opts for reopen:

reopen(path, mode_str) → ios

这实际上似乎有点有用,而不是重新打开(other_IO)→ios 选项。

This actually seems somewhat useful as opposed to the reopen(other_IO) → ios option.

这篇关于重新打开IO流与仅使用新流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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