为什么这个简单的Ruby程序不会打印出我期望的内容?

1 ruby temporary-files

我有这个:

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上.

sco*_*ttd 6

问题是你正在read对文件中的当前IO指针进行操作,该指针在写入后已经结束.你需要做一个rewindread.在你的例子中:

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)