我有这个:
require 'tempfile'
t = Tempfile.new('test-data')
t.open
t.sync = true
t << "apples"
t.puts "bananas"
puts "contents are [#{t.read}] (#{t.size} bytes)"
t.close
Run Code Online (Sandbox Code Playgroud)
这打印:
contents are [] (14 bytes)
Run Code Online (Sandbox Code Playgroud)
为什么内容实际上没有显示?我在Ruby 1.9.2上.
问题是你正在read对文件中的当前IO指针进行操作,该指针在写入后已经结束.你需要做一个rewind前read.在你的例子中:
require 'tempfile'
t = Tempfile.new('test-data')
t.open
t.sync = true
t << "apples"
t.puts "bananas"
t.rewind
puts "contents are [#{t.read}] (#{t.size} bytes)"
t.close
Run Code Online (Sandbox Code Playgroud)