Reopening IO Stream versus just using a new stream

An example is provided in Ruby-Docs:

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" 

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 or just using a new stream?

+4
source share
1 answer

I talked to some IRB developers some time ago, and the answer I received was that it was mainly used to change $std variables to change where methods such as puts and print are output to ...

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

Reason for using this, not ...

 $stdout = File.open('log') 

... was curious in the air. I had one developer who said direct assignment doesn't work very well with some ruby ​​C. functions I don't know much about C and can't say much about it, but he pointed me to the minitest source to see an example of this in use. However, apparently, even the source switched to a direct appointment against reopening, since the last of them looked at him.

In conclusion ... from his views, IO#reopen may be useless, but I would like to hear an argument against this.

Update

Ok, so I re-read the documentation and saw that there is a second set of options for reopen :

 reopen(path, mode_str) β†’ ios 

This does seem somewhat useful, unlike the reopen(other_IO) β†’ ios option.

+1
source

All Articles