在Ruby脚本中,我想处理源文件的前几行(用.readline
读取),然后将源文件的其余部分复制到目标文件(用{{1} })。但是,IO.copy_stream
似乎没有“看到”源文件的其余部分。
这里是重现问题的方法:
IO.copy_stream
这是输出:
require 'rspec'
require 'tempfile'
def file_create(content)
Tempfile.open('foo') do |src|
src.print content
src.close
yield src.path
end
end
describe :copy_stream do
it 'copies the content of an open file' do
file_create("a\nb\n") do |path|
open(path) do |from|
Tempfile.open('bar') do |to|
IO.copy_stream(from, to)
to.close
expect(IO.read(to.path)).to eq "a\nb\n"
end
end
end
end
it 'copies the rest of an open file' do
file_create("a\nb\n") do |path|
open(path) do |from|
Tempfile.open('bar') do |to|
to.print from.readline
IO.copy_stream(from, to)
to.close
expect(IO.read(to.path)).to eq "a\nb\n"
end
end
end
end
end
为什么Failures:
1) copy_stream copies the rest of an open file
Failure/Error: expect(IO.read(to.path)).to eq "a\nb\n"
expected: "a\nb\n"
got: "a\n"
(compared using ==)
Diff:
@@ -1,3 +1,2 @@
a
-b
[...]
2 examples, 1 failure
Failed examples:
rspec /workspaces/socbm378/johanabt/incstrip/spec/copy_stream_spec.rb:27 #
copy_stream copies the rest of an open file
无法复制文件的其余部分?
我找到了一个简单的解决方法,但是我想了解潜在的问题。这是我的解决方法:
copy_stream